File operations (file reading and writing)

 1. What is a file?

Files on disk are files.
But in programming, we generally talk about two types of files: program files and data files (classified from the perspective of file function).
1.1 Program files
Comprehensive source program preface (backwards .c ) , Object title ( windows Environment back order .obj ) environment windowspossible process order ( ,
后缀为 .exe ).
1.2 Data files
The content of the file is not necessarily the program, but the data read and written when the program is running, such as a file from which data needs to be read when the program is running.
Or a file with output content.
This time, we are mainly discussing data files
1.3 File name
A file must have a unique file identifier to facilitate user identification and reference. The file name contains 3 parts: file path + file name stem +< /span> File suffix
例如: c:\code\test.txt
For convenience, file identifiers are often referred to as file names .

2. Opening and closing files

2.1 File pointer
Continue to write the text, the key concept is Text item type indicator 、Simplified name letter code .
Each used file opens a corresponding file information area in the memory to store file-related information (such as file name, file status and current location of the file, etc.). This information is stored in a structure variable. The structure type is declared by the system and named FILE.
Whenever a file is opened, the system will automatically create a variable of the FILE structure based on the file's condition and fill it with the information. , generally a FILE pointer is used to maintain the variables of this FILE structure, which is more convenient to use.
2.2 Opening and closing files
The file should be opened before reading and writing, and the file should be closed after use /span> .
When writing a program, when opening a file, a FILE* pointer variable pointing to the file will be returned, which is equivalent to The relationship between pointers and files is established.
Standard C stipulates that the fopen function is used to open the file, fclose To close the file.
// Opening statement
FILE * fopen ( const char * filename , const char * mode );
// 关闭文品
int fclose ( FILE * strea
File opening method meaning If the specified file does not exist
"r" (read only)
To enter data, open an existing text file
Error
"w" (write only)
To output the data, open a text file
Create a new file
Create a new file
“a” (add)
Add data to the end of text file
Create a new file
“rb” (只读)
To enter data, open a binary file
Error
“wb” (just copy)        
To output data, open a binary file
Create a new file
“ab” (add)
Add data to the end of a binary file
Error
“r+” (translation)
For reading and writing, open a text file
Error
“w+” (translation)
For reading and writing, a new file is recommended
Create a new file
“rb+” (translation)
Open a binary file for reading and writing
Error
“wb+” (translation)
For reading and writing, create a new binary file
Create a new file
“ab+” (translation)
Open a binary file and read and write at the end of the file
Create a new file

For example:

/* fopen fclose example */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  //打开文件
  pFile = fopen ("myfile.txt","w");
  //文件操作
  if (pFile!=NULL)
 {
    fputs ("fopen example",pFile);
    //关闭文件
    fclose (pFile);
 }
  return 0;
}

3. Sequential reading and writing of files

Function
Function name
Applicable to
Character input function
fgetc
all input streams
character output function
fputc
All output streams
Text line input function
fgets
all input streams
Text line output function
fputs
All output streams
Format input function
fscanf
all input streams
Format output function
fprintf
All output streams
binary input
fread
document
binary output
fwrite
document

example:

//fscanf——格式化输入函数
#include<stdio.h>
struct S
{
	float f;
	char c;
	int a;
};
int main()

{
	struct S s = {0};
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fscanf(pf,"%f %c %d", &(s.f), &(s.c), &(s.a));
	printf("%f %c %d", s.f, s.c, s.a);
	
	fclose(pf);
	pf = NULL;
	return 0;
}

4, Determination of the end of file reading

4.1 feof

During file reading, cannot be used feof The return value of the function is directly used to determine whether the file is ended.
Instead is used when the file reading ends to determine whether the reading fails or the end of the file is encountered .
(1)  Text body matter is taken or not, judgment is returned is or not EOF ( < /span> ) fgets ( NULL ), some fgetc
For example:
fgetc Judgment right or wrong EOF .
fgets Return judgment whether or not NULL .
(2)  Judge the end of reading of binary files and determine whether the return value is less than the actual number to be read.
For example:
fread Determine whether the return value is less than the actual number to be read.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int c; // 注意:int,非char,要求处理EOF
    FILE* fp = fopen("test.txt", "r");
    if(!fp) {
        perror("File opening failed");
        return EXIT_FAILURE;
   }
 //fgetc 当读取失败的时候或者遇到文件结束的时候,都会返回EOF
    while ((c = fgetc(fp)) != EOF) // 标准CI/O读取文件循环
   { 
       putchar(c);
   }
  if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp))
        puts("End of file reached successfully");
    fclose(fp);
}

5. File buffer

ANSIC The standard adopts " buffered file system "< For data files processed by /span> compilation system. . The data output from the memory to the disk will be sent to the buffer in the memory first, and then sent to the disk together after the buffer is filled. If data is read from the disk to the computer, the data is read from the disk file and input into the memory buffer (the buffer is filled), and then the data is sent from the buffer to the program data area (program variables, etc.) one by one. The size of the buffer is determined by the C file buffer in the memory for each file being used in the program. , the so-called buffer file system means that the system automatically opens up a "
                                                                                                                                                                         

 example:

#include <stdio.h>
#include <windows.h>
int main()
{
	FILE* pf = fopen("test.txt", "w");
	fputs("abcdef", pf);//先将代码放在输出缓冲区
	printf("睡眠10秒-已经写数据了,打开test.txt文件,发现文件没有内容\n");
	Sleep(10000);//单位毫秒,也就是10s
	printf("刷新缓冲区\n");
	fflush(pf);//刷新缓冲区时,才将输出缓冲区的数据写到文件(磁盘)
	
	printf("再睡眠10秒-此时,再次打开test.txt文件,文件有内容了\n");
	Sleep(10000);
	fclose(pf);
	//注:fclose在关闭文件的时候,也会刷新缓冲区
	pf = NULL;
	return 0;
}
Because of the existence of the buffer, C language needs to refresh the buffer when operating a file or when the file operation ends. Close the file. Failure to do so may cause problems reading and writing files.

Guess you like

Origin blog.csdn.net/weixin_67131528/article/details/133935927