Knowledge point 13: files

1. File opening and closing

fopen function: fp = fopen(文件名, 使用文件方式);If the file fails to open, NULL (ie 0) will be returned.

	FILE *fp;
	if((fp = fopen("F:\\test.txt", "w")) == NULL)//文件名的输入必须用双斜杠,以与转义字符区分。如果文件与该c文件在同一个文件内,则可以直接写出文件名即可;若不在一起,则要完整地输入文件标识(含途径)
	//或者也可以:if( !(fp = fopen("F:\\test.txt", "w")) )
	{
    
    
		printf("error!");
		exit(0); //exit在stdlib头文件内,作用:关闭所有文件,终止正在执行的程序
	}//设置一个文件打开失败检测步骤
	理论上每一条关于文件的操作之后都应该判断是否成功 
	else printf("open successfully!");
	fclose(fp);
	FILE *fp;
	char ch, filename[20];
	printf("请输入文件名:");
	scanf("%s", filename);
	ch = getchar();//用scanf输入字符串时,回车表示输入的字符串到此结束,但“回车”符仍保留在缓冲区中,因此需要加一个getchar()来将其读取,即“消化”掉,从而避免之后会将其作为有效字符读取。
	if ( !(fp = fopen(filename, "r+")) )//数组名即一个指针! 
	{
    
    
		printf("can not open the file!\n");
		exit(0);
	}

In order to prevent data loss caused by closing source files, all files should be closed before the end of the program.
The fclose function fclose(文件指针);will return 0 if it is closed successfully; otherwise, it will return EOF.

2. File reading and writing

Pay attention to how the file is read and written

1, read and write a single character

fputc function:
write a character (character constant, character variable) to the disk file. fputc(ch, fp);If the output is successful, the inputted character will be returned; if the output fails, it will return EOF.

	ch = getchar();//从缓冲区接收键盘输入的第一个字符
	/*调用getchar()函数时,输入的字符被存放到缓冲区中,直到按回车为止(回车符也放到缓冲区中),
	之后getchar()函数才开始从缓冲区中每次一个地读入字符和其它操作,直到缓冲区的字符读完后才重新等待用户输入*/ 
	while (ch != EOF)
	{
    
    
		fputc(ch, fp);//回车也会输出
		ch = getchar();//直接从缓冲区读取
	}

fgetc function:
read a character from a disk file. ch = fgetc(fp);EOF is returned when the end of file is read.
c That character, just enter a character (single quotation marks) to the file

2. Read and write strings

fgets function:
read a string from a file and store it in a character array. char *fgets(char *str, int n, FILE *stream)Where n is the maximum number of characters that can be read each time. In fact, only n-1 characters can be read at most, and the last character is'\0', which serves as the end of the string.
When (n-1) characters are read, or when a newline character is read (the newline character is also read and stored in the array ), or when the end of the file is reached, the reading ends. If the end of the file is reached or no characters have been read, NULL is returned.
In the same array, when the fgets function is called for the second time, all the data in the array will disappear, and the storage will start from str[0] again.

	//可以通过 一次一次的 读取,最终读取所有内容 
	while (fgets(str, n, fp) != NULL)
	{
    
    
		printf("%s", str);
	} 

fputs function:
input the string in the character array into the file: the int fputs(const char *str, FILE *stream)input character does not include the end character'\0' of the string, so in order to prevent the input string from being connected together, it needs to be separated artificially fputs("\n",fp);. If the input is successful, a non-negative value is returned, otherwise EOF is returned.
There are two small differences between fputs() and puts():
1. puts() can only output to the standard output stream (ie screen output), while fputs() can output to any stream.
2. When using puts(), the system will automatically add a newline character after it; while using fputs(), the system will not automatically add a newline character, so sometimes it is necessary to manually enter a newline character.fputs("\n", fp);

3. Format input and output

fprintf function:
input data into the file in the specified format: int fprintf(FILE *stream, const char *format, ...)if successful, it returns the total number of characters written, otherwise it returns a negative number.
fscanf function:
read data from a file and assign it to a variable in the program: int fscanf(FILE *stream, const char *format, ...)if successful, this function returns the number of successful matches and assignments. If the end of the file is reached or a read error occurs, EOF is returned.

	FILE *fp;
	if( ( fp = fopen("F:\\test.txt", "a") ) == NULL )//注意文件的访问方式 
	{
    
    //比如这里应用a追加的方式,因为之后还需要读取文件中的数据,如果用w则是将文件全部清空,再重新从文件起始处输入,会使之后读取的数就是刚刚输入的数 
		printf("error!");
		exit(0);	
	}
	int i = 200, j;
	fprintf(fp, "%d", i);//将i输出到fp所指的文件中 
	fclose(fp);
	fp = fopen("F:\\test.txt", "r");//关闭并重新打开文件,使指针回到文件初的位置 
	fscanf(fp, "%d", &j);//从fp所指的文件中读取数,赋给j 
	printf("%d", j);
	fclose(fp);

4. Read and write the entire block of data

fread function:
read count times from the file pointed to by fp, and read size bytes each time, and the read information is stored in the buffer address. fread(buffer, size, count, fp)The successful execution of the function will return the value of count.
fwrite function:
output the information starting from the buffer address count times, and write size bytes to the file pointed to by fp each time. fwrite(buffer, size, count, fp)The successful execution of the function will return the value of count. The
fread and fwrite functions are used for the input and output of binary files, because they process the input and output according to the length of the data block, and no character conversion occurs.

   FILE *fp;
   char c[] = "This is runoob";
   char buffer[20];
   fp = fopen("file.txt", "w+");
   
   /* 写入数据到文件 */
   fwrite(c, strlen(c) + 1, 1, fp);//一个字符占一个字节

   fseek(fp, 0, SEEK_SET);//将文件指针移到文件开头
 
   /* 读取并显示数据 */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp);

The fread and fwrite functions are often used to process arrays and structure types, combined with the sizeof function

struct Student
{
    
    
	char name[10];
	int num;
	int math;
}score[100];

for (i = 0; i < n; i ++)
	if (fwrite(&score[i], sizeof(struct Student), 1, fp) != 1)//函数执行成功会返回count的值(此处为1)
		printf("error");

fread(&score[i], sizeof(struct Student), 1, fp);

3. The location of the file

1. The most basic situation: close the file and then open the file to make the file position pointer return to the beginning of the file.

2. Use the rewind function to return the file position pointer to the beginning of the file. rewind(fp);This function has no return value.

3. At the end of all the contents of the file will be followed by an end-of-file mark EOF.
The feof function can be used to detect whether the end-of-file mark has been read. When EOF is not read (that is, the file is not read to the end), the value of the feof function is 0; when the file is read, the value of feof is 1.
Common usage:while( !feof(fp) )

4. Use the ftell function to get the current position of the file position pointer. The value of the ftell function is the distance (relative displacement) from the beginning of the file.

	fp=fopen("F:\\test\\a.txt","r");
	
	printf("%d ",ftell(fp));//开始时,"文件读写位置标记"位于第一个字节,又ftell输出的是相对于文件开头的位移量来表示 
	                        //因此此时ftell的值为0                                      相对位置!!! 
	while(!feof(fp))
	{
    
    
		putchar(fgetc(fp));//fgetc函数直接作参数
		printf("%d ",ftell(fp));//每访问完一个字节后,读写位置自动后移一个字节,即ftell的返回值自动+1 
	}                           //此时位置读写标记指向的是一个还没有被访问的字节 

After accessing the last character, the file position mark points to the back of the last character. This points to nothing, but when the byte is read, -1 will be read, that is, the end of the EOF file, the file pointer will not move back, and a long space will be output when putchar(-1). Note: Don't think that the value -1 is stored in the last byte. This is just a processing method.
When EOF is read, the value of the feof function changes.

5. With the help of the fseek function, the position pointer can be moved to achieve random reading and writing. The general format isfseek(文件指针, 位移量, 起始点);

Starting point Symbolic representation Digital representation
File header SEEK_SET 0
current position SEEK_CUR 1
End of file (at EOF) SEEK_END 2

"Displacement" indicates the number of bytes moved, and it is required to be long data so that there will be no error when the file length is greater than 64KB. Therefore, when a constant is used to represent the displacement, the suffix L must be added to convert it to the long type.
For example, the fseek(fp, -20L, 1);//表示将位置指针从当前位置向开头方向移动20个字节。
fseek function is usually used for binary files. Due to the conversion of text files, errors often occur in the calculated positions.

4. Error detection

1, ferror function: int ferror(FILE *stream)
detect file errors in a given stream. If there is no error, it returns 0; if there is an error, it returns a non-zero value.
When the fopen function is executed, the initial value of the ferror function is automatically set to 0 (regardless of whether the file is successfully opened or not). If some errors were introduced in the file during the last file operation, through the ferror() function, we can determine that there were some errors in the file during the last operation.

   if( ferror(fp) )
      printf("error");
   clearerr(fp);//注意clearerr函数的写法,末尾有两个r

The clearerr function should be called immediately after calling the ferror function to change the value of the ferror function to 0 again, so that the next test can be performed; otherwise, the value of the ferror function will remain until the clearerr or rewind function or any other input is called Output function

Guess you like

Origin blog.csdn.net/Shao_yihao/article/details/113432775