C language learning summary _10 file operation

Several knowledge points summarized this time
1. Why use a file
2. What is a file
3. Open and close the
file 4. The sequential reading and writing
of the file 5. The random reading and writing
of the file 6. The classification
of the file 7. The end of the file reading Judgment
8, file buffer


1. Why use files?
When we use c to write a small application of the address book, when the address book program exits, the data in it does not exist. When the program is run next time, it needs to be re-entered. Isn’t it uncomfortable to use it? Can't the data be placed in a place where it can be stored permanently? This involves the issue of data persistence, such as storing data in disks or databases.
Using files, we can put the data directly on the hard disk of the computer to achieve data persistence.
2. What is a file?
File = Content + Attributes
In the program design, it is divided into: program file and data file
2.1, program file.
Program files end with .c, end with .obj and end with .exe.
2.2. Data file
The content of the file is not necessarily the program, but the data read and written when the program is running, such as the file that needs to read data from when the program is running, or the file that outputs the content.
2.3. File name
A file must have a unique file identifier for users to identify and quote.
The file name consists of 3 parts: file path + file name trunk + file suffix
3. File opening and closing
3.1 File pointer
Each used file has opened up a corresponding file information area in the memory to store the related file Information (such as: the name of the file, the status of the file, and the current location of the file, etc.) This information is stored in a structure variable, the type of the structure is declared by the system, named FILE.
For example, the FILE* pf;
definition of pf is a pointer Pointer variable (structure pointer) for FILE type data. The file can be accessed through the information in the file information area. In other words, the file associated with it can be found through the file pointer variable.
File = file content + file attributes
3.2
The file should be opened before reading and writing, and the file should be closed after use.
When writing a program, when opening a file, it will return a FILE* pointer variable pointing to the file, which is equivalent to establishing the relationship between the pointer and the file.
Use fopen to open the file, fclose to close the file
Insert picture description here

int main()
{
    
    
	FILE* pf = fopen("myfile.txt", "a");
	if (pf == NULL)
	{
    
    
		printf("File open error!\n");
		system("pause");
		return 1;
	}
	else{
    
    
		fputs("不是个梦!", pf);
		fclose(pf);
	}
	system("pause");
	return 0;
}

The first formal parameter is the file name, and the second is the open mode. Please refer to http://www.cplusplus.com/reference/cstdio/fopen/?kw=fopen.
4. File sequence read and write
character input and output functions : Fgetc/fputc
text line input and output functions: fgets/fputs
formatted input and output functions: fscanf/fprintf
binary input and output: fread/fwrite
we can use fprintf to simulate printf
c language will open 3 standard input and output streams by default, and their types are also For FILE* respectively:
stdin------->standard input
stdout----->display
stderr------>display
Everything is a file.

int main()
{
    
    
	fprintf(stdout, "chenzhihao is %s\n", "xiao ke ai!");
	system("pause");
	return 0;
}

5. Random (position) reading and writing of the
file fseek: locate the file pointer according to the position and offset of the file
ftell: return the offset of the file relative to the starting position
rewind: let the file read and write position return to the beginning of the file Start position.
For details, please refer to the following:
http://www.cplusplus.com/reference/cstdio/fseek/?kw=fseek
6. Classification of files
According to the organization form of the data, data files are converted into text files or binary files.
The data is stored in the memory in binary form. If it is output to the external memory without conversion, it is a binary file.
If it is required to store in the form of ASCII code on the external memory, it needs to be converted before the village school. A file stored in the form of ASCII code is a text file.
7. Judgment of the end of file reading. Remember
that feof used incorrectly
: In the process of reading the file, the return value of the feof function cannot be used directly to judge whether the file is over, but it is applied when the file reading ends. It is judged whether the end of the reading fails or the end of the file is encountered.
1) Whether the text file reading is finished, judge whether the return value is EOF (fgetc), or NULL (fgets)
, that is:
fetc judges whether it is EOF
fgets judges whether the return value is NULL
2)
Whether the binary file reading is finished is judged: Determine whether the return value u is less than the number to be read.
fread determines whether the return value is less than the actual number to be read.
The code of the text file is as follows:

int main()
{
    
    
	FILE* pf;
	int n = 0;
    pf = fopen("czh.txt", "r");
	if (NULL == pf){
    
    
		puts("File Open error!");
	}
	else{
    
    
		while (fgetc(pf) != EOF){
    
    
			n++;
		}
		//程序走到这里证明跳出循环,也就是文件读取结束,然后要feof判断
		//读取结束的原因
		if (feof(pf)){
    
    
			printf("文件总字符数为:%d\n", n);
		}
		else{
    
    
			puts("End of file is not reached!");
		}
		fclose(pf);
	}


	system("pause");
	return 0;
}

Examples of binary files:

#define SIZE 10
int main()
{
    
    
	//二进制文件文件的读写
	double a[SIZE] = {
    
     3.10, 3.11, 3.12, 3.13, 3.14, 3.15, 3.16, 3.17, 3.18, 3.19 };
	FILE* pf = fopen("data.txt", "wb");
	if (pf == NULL){
    
    
		puts("File open error!");
	}
	else{
    
    
		fwrite(a, sizeof(double), SIZE, pf);
		fclose(pf);
	}
	pf = fopen("data.txt", "rb");
	if (pf == NULL){
    
    
		puts("File open error!");
	}
	else{
    
    
		double b[3] = {
    
     0.0 };//缓冲区
		while (1){
    
    
		   size_t s=fread(b, sizeof(double), 3, pf);
		   if (s < 3){
    
    
			   break;
		   }
		   //对读到的元素进行操作
		}
		if (feof(pf)){
    
    
			puts("read file of end....!");
		}
		/*while (fread(b, sizeof(double), 3, pf)>0)
		{
			for (int i = 0; i < 3; i++){
				printf("%f\n", b[i]);
			}
		}*/
		fclose(pf);
	}
	system("pause");
	return 0;
}

or:

int main()
{
    
    
	//二进制文件文件的读写
	double a[SIZE] = {
    
     3.10, 3.11, 3.12, 3.13, 3.14, 3.15, 3.16, 3.17, 3.18, 3.19 };
	FILE* pf = fopen("data.txt", "wb+");
	if (pf == NULL)
	{
    
    
		puts("File open error!");
	}
	else
	{
    
    
		fwrite(a, sizeof(double), SIZE, pf);
		//int pos_0 = ftell(pf);
		//printf("pos_0 = %d\n", pos_0);
		rewind(pf);//让文件读取位置回到其实位置,避免重新关闭和打开
		//int pos_1  = ftell(pf);
		//printf("pos_1 = %d\n", pos_1);
		double b[3] = {
    
     0.0 };//读缓冲区
		while (1)
		{
    
    
			size_t s = fread(b, sizeof(double), 3, pf);
			if (s < 3)
			{
    
    
				break;
			}
		}
		if (feof(pf))
		{
    
    
			puts("End of file is reached!\n");
		}
		else
		{
    
    
			puts("file read error!");
		}
		fclose(pf);
	}
	
	system("pause");
	return 0;
}

8. The file buffer
c program provides a buffer mechanism by default. The so-called buffer mechanism is a buffer. The buffer is essentially a piece of memory. Its existence value is to improve efficiency. You can understand it as express delivery.
Common buffering mechanisms are: 1) No buffering 2) Line buffering 3) Full buffering
Line buffering: use special symbols as a buffer refresh mark such as "\n",
full buffering: refresh the buffer when the buffer is full, forced refresh, The program exits.
Display files are line buffered and unbuffered,
ordinary files are fully buffered

Guess you like

Origin blog.csdn.net/CZHLNN/article/details/110238501