C language--the role of files and related operations

This article mainly introduces some operations and usage of files in C language

What is the role of the document?

During the normal running of the program, the file data generated during the running of the program will be destroyed at the end of the program, so how to store this information, or how to read some information from the file and save it? At this time, the related operations of the file are used.
In this way, the data can be directly placed on the hard disk of the computer to achieve data persistence.

What is a document?

Generally speaking, a file refers to a file on disk.

In programming, we divide files into two categories, one is program files and the other is data files

program files

Program files are the .c files we see, or .obj files, or .exe files are all program files

data file

Data files refer to these files that generate data during the running of the program. The related function of the introduction file is to output information to the disk, and then read these files from the disk into the program when necessary. This process is This article discusses how to achieve

file pointer

The key concepts to be introduced first are file type pointers and file pointers

When we want to use a file, we will open up a corresponding file information area in the memory to store the information of related files, and this information is stored in a structure. In C language, this The structure has a specific definition, and the c language defines it asFILE, in vs, there is a specific definition of FILE as follows:

struct _iobuf 
{
    
    
    char *_ptr;
    int  _cnt;
    char *_base;
    int  _flag;
    int  _file;
    int  _charbuf;
    int  _bufsiz;
    char *_tmpfname;
};
typedef struct _iobuf FILE;

It can be seen that in fact, a structure is defined in the c language, which contains various members required by the file, and then the entire structure is renamed to FILE

So when we want to create a file information, we can use this file pointer to maintain the file, which can be more convenient, so there is the following line of writing

FILE* pf;//文件指针变量

The defined pf is a pointer variable pointing to FILE type data, which can make pf point to the information area of ​​a file, and the file can be accessed through the information in the file information area, that is to say, the file pointer variable can be used to find and its associated files

file opening and closing

After introducing the file pointer, we can introduce the operation of opening and closing the file.

In the c language, the operation of the file is often divided into three parts: opening the file, operating the file, closing the file

So first of all, let's learn how to open and close files.

In the c standard, there is such a function, fopen is used to open the file, and fclose is used to close the file

//打开文件
FILE * fopen ( const char * filename, const char * mode );
//关闭文件
int fclose ( FILE * stream );

The following is an example of the related operations of opening and closing files

#include <stdio.h>
int main()
{
    
    
	//文件的打开
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen\n");
		return 1;
	}
	//进行文件的相关操作
	fputs("打开文件成功!\n",pf);
	//关闭文件
	fclose(pf);
	return 0;
}

The result of the operation is as follows
insert image description here
It can be seen that a test.txt file will indeed be created in the local disk, and the relevant information required by the code will be saved in the file

The fputs function in the code will be explained later

Sequential reading and writing of files

If you want to store a piece of information in a disk file in a program, you must have a function. Only through the function can you put the information in the disk file.

Here are some read and write functions

insert image description here
Introduction to the various functions mentioned above


fgetc

This function is to read a character from an external file into the program, we can write the following program for verification

Suppose the following information is stored in the test.txt file
insert image description here
Then we write the following program statement

#include <stdio.h>

int main()
{
    
    
	//打开文件
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen\n");
		return 1;
	}
	//对文件进行操作
	char ch = fgetc(pf);
	printf("%c\n", ch);//a
	ch = fgetc(pf);
	printf("%c\n", ch);//b
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

Let’s analyze the program, first open the file, abcdef has been stored in advance in the local file to be opened, so when we call the fgetc function, it will read a character in the local file and store it in the file we defined good variable ch

Then print out ch to output the information to the screen

A phenomenon can be found from this code. After reading character a, the pointer will point directly to character b , and wait for the next fgetc command to directly read character b. Regarding the pointer pointing problem, there will be related functions to introduce later

insert image description here

It can be seen that fgetc can only read one character


fputc

Like fgetc, it outputs a character to a local file, and also only outputs one character

The code is implemented as follows

#include <stdio.h>

int main()
{
    
    
	//打开文件
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return 1;
	}
	//对文件进行操作
	fputc('a', pf);
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

fgets/fputs

Compared with fgetc/fputc, it can interact with strings

The code is implemented as follows:

//对文件的写入
#include <stdio.h>
int main()
{
    
    
	FILE* pf;
	//打开文件
	pf = fopen("text1.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen:");
		return 1;
	}
	//操作文件
	char arr[] = "helloworld";
	fputs(arr, pf);
	fclose(pf);
	return 0;
}
//把文件进行输出
#include <stdio.h>
int main()
{
    
    
	FILE* pf;
	//打开文件
	pf = fopen("text1.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen:");
		return 1;
	}
	//操作文件
	char str[20];
	fgets(str, 20, pf);
	printf("%s", str);
	fclose(pf);
	return 0;
}

Compare a set of input and output functions

对比scanf/fscanf/sscanf/printf/fprintf/sprintf

scanf is a formatted input function for the standard input stream (stdin)
printf is a formatted output function for the standard output stream (stdout)
fscanf is a formatted input function for all input streams
fprintf is a formatted output function for all output streams
sscanf converts strings into formatted data
sprintf converts formatted data into strings

Random reading and writing of files

fseek function

The fseek function locates the file pointer based on the position and offset of the file pointer

The code display function is as follows:

#include <stdio.h>
int main()
{
    
    
	FILE* pf;
	//打开文件
	pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen;");
		return 1;
	}
	//操作文件
	char ch[] = "abcdef";
	fputs(ch, pf);
	//关闭文件
	fclose(pf);
	pf = NULL;
	FILE* pf2;
	pf2 = fopen("test.txt", "r");
	if (pf2 == NULL)
	{
    
    
		perror("fopen:");
		return 1;
	}
	//操作文件
	printf("%c\n", fgetc(pf2));//读取a
	printf("%c\n", fgetc(pf2));//读取b,此时指向c
	fseek(pf2, -1, SEEK_CUR);//把文件指针从当前位置向左移动一位
	printf("%c\n", fgetc(pf2));//此时文件指向b,输出就是b
	fseek(pf2, 0, SEEK_SET);//把文件指针指向开始
	printf("%c\n", fgetc(pf2));
	//关闭文件
	fclose(pf2);
	pf2 = NULL;
	return 0;
}

ftell

Returns the offset of the file pointer relative to the starting position, similar to the above function

rewind

Let the position of the file pointer return to the beginning of the file, which is similar to the function of fseek

Guess you like

Origin blog.csdn.net/qq_73899585/article/details/131508793