Detailed explanation of file operations & related functions (super detailed!)

Table of contents

1. Document prerequisite knowledge

1. What is a document?

(1) Program files

(2) Data file

2. File name

3. File Type

4. File buffer

5. File Pointer

 Second, the file operation function

1. Open and close functions

(1) fopen()---Open the file

(2) fclose()--- close the file

2. Sequential reading and writing of files, the use of various functions

(1) fgetc and fputc -------- character input and output functions

  (2) fgets and fputs--- text input and output functions

(3) fscanf and fprintf --- format input and output functions

(4) fread and fwrite---binary input and output functions

3. File end judgment function

(1)feof


1. Document prerequisite knowledge

1. What is a document?

Files on disk are files. But in programming, we generally talk about two kinds of files: program files, data files

(1) Program files

  • Including source program files (suffix .c)
  • Object file (windows environment suffix is ​​.obj)
  • Executable program (windows environment suffix is ​​.exe)

(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 the file from which the program needs to read data, or the file that outputs the content.
This section discusses data files. 
   In the past, the input and output of processed data were all targeted at the terminal, that is, data was input from the keyboard of the terminal, and the running results were displayed on the monitor. In fact, sometimes we will output the information to the disk, and then read the data from the disk into the memory for use when needed. Here, the files on the disk are processed.

2. File name

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 .

3. File Type

Depending on how the data is organized, data files are called text files or binary files .
  • Data is stored in binary form in memory, and if it is output to external storage without conversion, it is a binary file .
  • A file stored in the form of ASCII characters is a text file . (If it is required to store in the form of ASCII code on the external storage, it needs to be converted before storage)

4. File buffer

The ANSIC standard uses the "buffer file system" to process data files. The so-called buffer file system means that the system automatically creates a " file buffer " in the memory for each file being used in the program . Data output from memory to disk will be sent to the buffer in memory first, and then sent to disk together after the buffer is filled. If data is read from the disk to the computer, the data read from the disk file is input to the memory buffer (full of the buffer), 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 compilation system. (purpose: to improve efficiency)

5.   File pointer

In the cache file system, the key concept is " file type pointer ", referred to as " file pointer ".
Each used file has opened up a corresponding file information area in the memory, which is used to store the relevant information of the file (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 structure type is declared by the system, named FILE .

 Second, the file operation function

1. Open and close functions

(1) fopen()---Open the file

FILE * fopen ( const char * filename, const char * mode );
filename: path string , if it is in the same folder as the source file, you can directly fill in  the file name + file type.
mode: Open mode, specify the character.
Here is a list of common opening methods:
How the file is used Meaning If the file does not exist
"r" (read-only) Open an existing text file for data entry Error
"w" (write only) Opens a text file for outputting data Creates a new file
"a" (append) Add data to the end of the text file Error
"rb" (read-only) Open a binary file for input data Error
"wb" (write only) Opens a binary file for data output Creates a new file

(2) fclose()--- close the file

int fclose ( FILE * stream );

use:
/* fopen fclose example */
#include <stdio.h>
int main ()
{
  FILE * pFile = fopen ("myfile.txt","w"); // 如果没有此文件,就会创建此文件。 
  //                                          同时,会销毁原文件数据
  if (pFile ==NULL)
 {
    perror("fopen");  // 打印fopen失败原因
    exit(-1);
 }
  .....录入数据
  fclose(pFile);
  pFile = null; // 防止后边解应用
  return 0;
}

2. Sequential reading and writing of files, the use of various functions

Function Function Name Applies to
Character input function fgetc all input streams
The 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
Formatted output function fprintf all output streams
binary input fread file
binary output fwrite file

(1) fgetc and fputc -------- character input and output functions

Code usage example:
#include<stdio.h>
int main()
{
	FILE* a =  fopen("Test.txt", "w");
	if (a ==NULL)
	{
		perror("fopen");
		exit(-1);
	}
	fputc('a', a);  // 输出
	fputc('b', a);
	fputc('c', a);
	fputc('d', a);
	fputc('e', a);
	fclose(a);

	a = fopen("Test.txt", "r");  // 重新打开文件
	int ch = 0;
	while ((ch = fgetc(a)) != EOF)
	{
		printf("%c ", ch);
	}
	fclose(a);  // 关闭文件
	a = NULL;
	return 0;
}

result:


(2) fgets and fputs--- text input and output functions

Code example:

#include<stdio.h>

int main()
{
	FILE* a = fopen("test.txt", "w");// 以 只写 方式打开文件
	if (a ==NULL)
	{
		perror("fopen");
		exit(-1);
	}
	fputs("abcdefgh", a);
	fclose(a);

	a = fopen("test.txt", "a");  // 重新以  增添  方式打开文件
	fputs("ahuang", a);
	fclose(a);

	a = fopen("test.txt", "r");  // 重新以 只读 方式打开文件
	char* c[20] = { 0 };
	fgets(c, 20, a); // 会少打印一个字符,因为要留个位置给\0。
	printf("%s", c);
	fclose(a);
	a = NULL;
	return 0;
}

result:


 (3) fscanf and fprintf --- format input and output functions

#include<stdio.h>
struct MyStruct
{
	char name[20];
	int age;
	double size;
};

int main()
{
	struct MyStruct s = { "ahuang", 20 ,60};
	// 打开文件
	FILE* a = fopen("Test2.txt", "w");
	if (a == NULL)
	{
		perror("fopen");
		exit(-1);
	}
	fprintf(a, "%s %d %lf", s.name, s.age, s.size);
	fclose(a);

	a = fopen("Test2.txt", "r");
	struct MyStruct c = { 0 }; // 接收文件读取的数据
	fscanf(a,"%s %d %lf", c.name, &(c.age), &(c.size));
	fprintf(stdout, "%s %d %lf\n", c.name, c.age, c.size); // 打印到屏幕
    // 上一段等价于 printf("%s %d %lf", c.name, c.age, c.size);
	fclose(a);
	a = NULL;
	return 0;
}

result:

To add here, when a C program starts, the following three information streams are opened by default:

The standard input stream, stdin, comes from the keyboard

The standard output stream, stdout, is output to the display

The standard error stream, stderr , is output to the display

 (4) fread and fwrite---binary input and output functions

The code is used as follows:

#include<stdio.h>
struct MyStruct
{
	char name[20];
	int age;
	double size;
};

int main()
{
	FILE* p1 = fopen("Text.txt", "w");
	struct MyStruct k = { "阿黄", 20, 89 };
	fwrite(&k, sizeof(struct MyStruct), 1, p1);
	fclose(p1);

	p1 = fopen("Text.txt", "r");
	struct MyStruct z = { 0 };
	fread(&z, sizeof(struct MyStruct), 1, p1);
	printf("%s %d %lf", z.name, z.age, z.size);
	return 0;
}

result:

 Here is a supplement: why the binary input and output data will be garbled in Notepad:

     Presentation does not match

     Analysis: The first three input and output methods are saved in ASCII format, which is a text file; the last one is saved in binary format, and if the data opened with Notepad is saved in ASCII format, the binary format will be garbled.

3. File end judgment function

(1)feof

Keep in mind: during the file reading process, the return value of the feof function cannot be used to directly determine whether the file is over.
Instead, it is applied to when the file reading ends, judging whether the reading fails to end, or the end of the file is encountered .
1. Whether the reading of the text file is finished, judge whether the return value is EOF (fgetc) or NULL (fgets)
For example:
  • fgetc judges whether it is EOF.
  • fgets determines whether the return value is NULL.
2. Judging the end of reading the binary file, and judging whether the return value is less than the actual number to be read.
For example:
  •       fread judges whether the return value is less than the actual number to be read.
Correct usage:
Example of a text file:
}
#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) // 标准C I/O读取文件循环
  {
      putchar(c);
  }
//判断是什么原因结束的
   if (ferror(fp))     // 如果ferror返回非0,那么中间出现错误。
       puts("I/O error when reading");
   else if (feof(fp))  // 判断是否遇到EOF才结束,是就是正常结束。
       puts("End of file reached successfully");
   fclose(fp);
}

   epilogue

This section is over here, thank you friends for browsing, if you have any suggestions, welcome to comment in the comment area, if you bring some gains to your friends, please leave your likes, your likes and concerns will become bloggers The driving force of the master's creation .

Guess you like

Origin blog.csdn.net/qq_72112924/article/details/130170138