Reading and writing files in C language

Don't win or lose, just ask right or wrong

Article directory

1. Overview of the document  

2. What is reading and writing files

Third, the function of file processing

1. File opening and closing

2. Sequential reading and writing of files

Sequential reading and writing related functions of files

Comparison and distinction between scanf and printf families

3. Random reading and writing of files      

Random read and write functions for files

4. File buffer

5. Judgment of the end of reading the file

Two criteria for judging whether the file has been read

misused feof


  Hello everyone, I am Ji Ning. As a qualified programmer, you must understand the mechanism of file creation and use in the program. This article will introduce the content related to files in C language.

1. Overview of the document  

  Files are a very important part of the computer system. They are often used to store various information such as documents, pictures, tables, letters, videos, etc. Using files, we can store data directly on the hard disk of the computer, which can achieve data persistence change. Then, it is very important to learn to read and write files or create files in the program. 

  In programming, we generally talk about two types of files: program files and data files. Program files refer to the files of the program itself, such as source files (with the suffix of .c), object files (with the suffix of .obj), and executable files (with the suffix of .exe under the Windows system); and data files refer to the programs running When reading and writing data, this article discusses data files.

  A file must have a unique file identifier for user identification and reference. The file name consists of 3 parts: file path + file name trunk + file suffix . For example: c:\code\test.txt . For convenience, the file ID is often referred to as the file name.

  In C, a file is viewed as a sequence of bytes, each of which can be read individually. C provides two file modes: text mode and binary mode .

  To distinguish between text mode and binary mode, one thing must be clear first, the contents of all files are stored in binary form (0 or 1). And if the file originally used binary encoded characters to represent text, then the file is a text file, which contains text content; if the binary values ​​in the file represent machine language or numeric data or some musical encoding, then the file is a binary file , which contains binary content.

2. What is reading and writing files

  Reading a file is to read a file, and read out the content of the file in the hard disk for use. Writing a file is to write data to a specific file on the hard disk, so that it can be read next time. Reading a file is equivalent to input, and writing a file is equivalent to output. For a program, reading data from a file is equivalent to inputting data from the keyboard; writing data to a file is equivalent to outputting data on the screen.

Third, the function of file processing

1. File opening and closing

  Use the fopen() function in C language to open the file. This function is declared in <stdio,h>. The first parameter is a pointer pointing to the address of the opened file, usually also called the file pointer. The second parameter is a string specifying the mode of the file to be opened. The following table provides some commonly used modes in C.

pattern string meaning
"r" open file for reading
"w" Open the file in write mode, and delete all the existing content of this file, if the text does not exist, create a file
"a" Open the file in write mode, append content to the end of the file, or create a file if it does not exist
"r+" Open the file in update mode (you can read and write the file)
"w+" Open the file in update mode (that is, it can be read and written). If the file exists, after reading the file content, all the content of the file will be deleted (the length is truncated to 0); if the file does not exist, a new file will be created
"a+" Opens the file in update mode (that is, can read and write), appends to the end of the existing file if it exists, or creates a new file if it does not exist; can read the entire file, but only appends from the end

"rb"、"wb"、"ab"、"rb"、"rb+"

"r+b"、"w+b"、"wb+"、"ab+"、"a+b"

After adding b to the string, the function is similar to the previous one, but the file is opened in text mode instead of binary mode

  After the program successfully opens the file, fopen() will return the file pointer ( file pointer ). The type of the file pointer is a pointer to FILE, and FILE is a type defined in <stdio.h>. But pf doesn't point to the actual file, it points to a data object containing the information file. For example, the following code for reading and writing files

    FILE* pf = fopen("mhj.txt", "r");//以文本模式读文件
	FILE* pf = fopen("mhj.txt", "w");//以文本模式写文件
	FILE* pf = fopen("mhj.txt", "rb");//以二进制模式读文件
	FILE* pf = fopen("mhj.txt", "wb");//以二进制模式写文件

  The fclose(pf) function can close the file specified by pf, and flush the buffer if necessary. If the close is successful, the fclos() function returns 0, otherwise it returns EOF. After closing, the pf pointer should be cleared in time to prevent pf from becoming a wild pointer.

    fclose(pf);
	pf = NULL;

2. Sequential reading and writing of files

Sequential reading and writing related functions of files

Function Function name apply to
character input fgetc all input streams
character output fputc all output streams
text line input fgets all input streams
text line output fputs all output streams
formatted input fscanf all input streams
formatted output fprintf all output streams
binary input fread document
binary output fwrite document

  The fgetc and fputc functions are similar to the getchar and putcgar functions, except that the latter reads (input) from the keyboard and writes (output) on the screen, while the former can input and output from all streams.

  For example: the following statement means to get a character from the standard input stream:

ch=getchar();

The same function, fgetc can also do:

ch=fgetc(stdin);

Of course, the main function of fgetc is to read characters from the file. The following statement means to get a character from the file specified by pf

ch=fgetc(pf);

  When using these file operation functions, you can imitate the usage of the standard input and output stream functions, you only need to pay attention to their parameters and the name of the file pointer to be written.

file input and output functions

Function return type and parameters
fgetc int fgetc ( FILE * stream );
fputc int fputc ( int character, FILE * stream );
fgets char * fgets ( char * str, int num, FILE * stream );
fputs int fputs ( const char * str, FILE * stream );
fscanf int fscanf ( FILE * stream, const char * format, ... );
fprintf int fprintf ( FILE * stream, const char * format, ... );
fread size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
fwrite size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

Comparison and distinction between scanf and printf families

  The scanf and printf functions are only applicable to standard input and output streams, that is, input from the keyboard; while the fprint function and fscanf functions are used for all input and output streams, with a few more parameters. int sprintf ( char * str, const char * format, ... );

  The sscanf and sprintf functions have the function of converting data into strings. First observe the parameters and return values ​​of these functions

sscanf        int sscanf ( const char * s, const char * format, ...);
sprintf        int sprintf ( char * str, const char * format, ... );

  format means the format, one of the formats corresponds to a parameter, sscanf sprintf is the same as the standard input stream, but there is an extra pointer in the parameter list

  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);

The meaning of the above code is to convert all the data in the double quotes into a string and put it into the buffer.

3. Random reading and writing of files      

Random read and write functions for files

fseek int fseek ( FILE * stream, long int offset, int origin );
ftell long int ftell ( FILE * stream );
rewind void rewind ( FILE * stream );

  fseek函数:可以将文件看做数组,在fopen打开的文件中直接定位到任意字节处,根据文件指针的位置和偏移量来定位文件指针。

int main()
{
	FILE* pFile;
	pFile = fopen("example.txt", "wb");
	fputs("This is an apple.", pFile);
	fseek(pFile, 9, SEEK_SET);
	fputs(" sam", pFile);
	fclose(pFile);
	return 0;
}

  ftell函数:返回文件指针相对于起始位置的偏移量

​
#include <stdio.h>
int main()
{
	FILE* pFile;
	long size;
	pFile = fopen("myfile.txt", "rb");
	if (pFile == NULL) perror("Error opening file");
	else
	{
		fseek(pFile, 0, SEEK_END);  
		size = ftell(pFile);
		fclose(pFile);
		printf("Size of myfile.txt: %ld bytes.\n", size);
	}
	return 0;
}

​

rewind函数:让文件指针的位置回到文件的起始位置

#include <stdio.h>
int main()
{
	int n;
	FILE* pFile;
	char buffer[27];
	pFile = fopen("myfile.txt", "w+");
	for (n = 'A'; n <= 'Z'; n++)
		fputc(n, pFile);
	rewind(pFile);
	fread(buffer, 1, 26, pFile);
	fclose(pFile);
	buffer[26] = '\0';
	puts(buffer);
	return 0;
}

  上述代码的意思是先将字符A~Z写入文件 myfile.txt ,再用rewind函数使文件指针回到起始位置,再以二进制的形式读取它们。

四、文件缓冲区

  缓冲区,即临时储存数据的地方,可以提高效率节约时间。且缓冲区这个概念不止在文件里有。在平时输入输出的时候,也会有缓冲区,当用户打错字符的时候,可以直接通过键盘修正,最后按下Enter键,传输的才是正确的输入。下面以文件的缓冲区为例介绍缓冲区是如何提高效率的。

  如果内存从硬盘中拿数据的时候,硬板每输入一个数据,内存就拿一次,每输入一个数据,内存就拿一次......那么内存的内存读取的负担就会非常大,有些数据是源源不断的从硬盘传递过来的,所以就有了缓冲区这个概念。

  缓冲区是系统自动地在内存中为程序中每一个正在使用的文件开辟一块“文件缓冲区”。计算机从内存向磁盘输出数据会先送到内存中的缓冲区,装满缓冲区后才一起送到磁盘上;如果从磁盘向计算机读入数据,则从磁盘文件中读取数据输入到内存缓冲区(充满缓冲区),然后再从缓冲区逐个地将数据送到程序数据区(程序变量等),缓冲区的大小是由C原因的编译器自身决定的。

五、文件的读取结束的判定

判断文件是否读取结束的两个标准

  1. 文本文件读取是否结束,判断返回值是否为 EOF ( fgetc ),或者 NULL ( fgets )
例如:fgetc 判断是否为 EOF ,fgets 判断返回值是否为 NULL。

  2. 二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。
例如:fread判断返回值是否小于实际要读的个数。

被错误使用的feof

  feof函数的作用是:当文件读取结束的时候,判断是读取结束的原因是否是 遇到文件尾结束。要牢记:在文件读取过程中,不能用feof函数的返回值直接来判断文件的是否结束

在用上述两个方法判断是否结束后,在用feof函数判断读取结束的原因

//判断是什么原因结束的
if (ferror(fp))
	puts("I/O error when reading");
else if (feof(fp))
	puts("End of file reached successfully");

非常感谢各位对纪宁的支持,你们的支持就是我不断更新的动力

Guess you like

Origin blog.csdn.net/zyb___/article/details/131863870