[C language] file operation function


1. Opening and closing of files

1.1fopen

FILE * fopen ( const char * filename, const char * mode );
  1. The function of fopen is to open the file.
  2. The header file of fopen is <stdio.h>, the first parameter is the file name, and the second parameter is the method (how to open the file). If the file is opened successfully, it returns a pointer to the file information area, and if it fails to open, it returns NULL.
  3. The file is opened as follows:
file usage meaning If the specified file does not exist
"r" (read-only) To enter data, open an existing text file go wrong
"w" (write only) To output data, open a text file create a new file
“a” (append) Add data to the end of the text file create a new file
"rb" (read-only) To enter data, open a binary file go wrong
"wb" (write only) To output data, open a binary file create a new file
“ab” (append) append data to the end of a binary file go wrong
"r+" (read and write) Open a text file for reading and writing go wrong
"w+" (read and write) Create a new file for reading and writing create a new file
"a+" (read and write) Open a file for reading and writing at the end of the file create a new file
"rb+" (read and write) Open a binary file for reading and writing go wrong
"wb+" (read and write) Create a new binary file for reading and writing create a new file
"ab+" (read and write) Open a binary file for reading and writing at the end of the file create a new file

(1) The input and output here are from the perspective of memory, the input is from the file to the memory, and the output is from the memory to the file.
(2) What is a text file? What is a binary file again?
Data is stored in binary form in memory, and if it is output to external storage (file) without conversion, it is a binary file. If it is required to store in the form of ASCII code on the external storage (file), it needs to be converted before storage. A file stored in the form of ASCII characters is a text file.
(3) Don't look at so many opening methods, only "r", "w", "rb" and "wb" are commonly used in C.


1.2close

int fclose ( FILE * stream );
  1. The function of fclose is to close the file.
  2. (1) What is a stream? I think it is a medium for data input and output. Outputting data to the screen, outputting to a file, and inputting data from a file or keyboard all require the help of a stream.
    (2) Why do we usually print data and input data without streaming? When any C language program is running, three streams are opened by default: stdin: standard input stream (keyboard); stdout: standard output stream (screen); stderr: standard error stream (screen).
    (3) So we need streams when using file input and output. When we read and write data from a file, we need to go through the stream, so we can read and write directly from the stream. The stream is our file pointer, the type is FILE*, through this stream we can input data to the memory and output data to the file.
  3. Returns 0 if the file is successfully closed, or EOF if it fails. Also remember to set the pointer to NULL.

例子

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here


2. Sequential reading and writing of files

2.1 fgetc and fputc

2.1.1fputc

int fputc ( int character, FILE * stream );
  1. The function of fputc is to output characters to the stream. fputc works on all output streams (including stdout and files etc).
  2. The header file of fputc is <stdio.h>. The first parameter is the character to be input, and the second parameter is a pointer to the output stream. If the output is successful, the output character is returned, and if it fails, EOF is returned.

例子
First create a file.
insert image description here

int main()
{
	FILE* pf = fopen("test.txt", "w");//我们要写入文件,以写的形式打开
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	int i = 0;
	for (i = 'a'; i <= 'z'; i++)
	{
		fputc(i, pf);//文件里面有指示器,当输入一个字符时,指示器指示下一个位置。
	}
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here

2.1.2fgetc

int fgetc ( FILE * stream );
  1. The role of fgetc is to read characters from the stream. fgetc works on all input streams (including stdin and files etc.).
  2. The header file for fgetc is <stdio.h>. The parameter is a pointer to the input stream. If the reading is successful, return the ASCII code value of the read character, and return EOF if the reading ends or fails.

例子

int main()
{
	FILE* pf = fopen("test.txt", "r");//以读的形式打开文件
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	//读取文件
	int ch = 0;
	while (ch = fgetc(pf))//当读取一个字符后,指示器指向下一个字符
	{
		printf("%c ", ch);
		
	}
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here


2.2 fgets and fputs

2.2.1fputs

int fputs (const char * str, FILE * stream);
  1. What fputs does is write a string to a stream. fputs applies to all output streams.
  2. The header file of fputs is <stdio.h>. The first argument is a pointer to the string to be written to the stream, and the second argument is a pointer to the output stream. If the write is successful, it returns a non-negative number, and if it fails, it returns EOF.
  3. fputs writes strings to the stream and stops when it encounters '\0', but the '\0' at the end will not be written.

例子

int main()
{
	FILE* pf = fopen("test.txt", "w");//以"w"的形式打开,如果先前文件有内容就会被初始化
	if (NULL == pf)
	{
		perror("fopen");
	}
	fputs("hello world\n", pf);
	fputs("welcome", pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here

2.2.2fgets

char * fgets ( char * str, int num, FILE * stream );
  1. The role of fgets is to read a string from a stream. fgets works on all input streams.
  2. The header file for fgets is <stdio.h>. The first parameter is a pointer to an array, which is used to put the string read from the stream, and the second parameter is the number of characters read from the stream (actually read num-1 characters , the last character is left for \0), and the third parameter is a pointer to the input stream. If the read is successful, str is returned, and NULL is returned when the end of the file is read or the read fails. (How to distinguish between reading failure and reading to the end of the file will be discussed later)
  3. fgets reads the string from the stream until the end of num-1 characters, or until the end of the newline character (the newline character is also counted as num characters), or until the end of the file.

例子

int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	char arr[20] = { 0 };
	fgets(arr, 5, pf);
	printf("%s", arr);
	//fgets(arr, 8, pf);
	//printf("%s", arr);
	return 0;
}

结果
insert image description here
insert image description here


2.3 fscanf and fprintf

2.3.1fprintf

int fprintf ( FILE * stream, const char * format, ... );
  1. The function of fprintf is to format the data output to the stream. fprintf works on all output streams.
  2. The header file of fprintf is <stdio.h>. The first parameter is a pointer to the output stream, and the second parameter is a list of variable parameters, that is, there can be multiple parameters, which are not fixed. Returns the number of items output if the output was successful, or a negative number if it failed.

例子

struct Stu
{
	char name[20];
	int age;
	float score;
};
int main()
{
	struct Stu s = { "zhangsan",18,99.5 };
	FILE* pf = fopen("test.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fprintf(pf, "%s %d %f", s.name, s.age, s.score);
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here

2.3.2fscanf

int fscanf ( FILE * stream, const char * format, ... );
  1. The function of fscanf is to formattedly read data from the stream into the items in the parameter list. fscanf works on all input streams.
  2. The header file of fscanf is <stdio.h>. The first is a pointer to the input stream, and the second parameter is a variable parameter list. This function returns the number of items successfully filled in the argument list if the read was successful, or EOF if the read failed or reached the end of the file.

例子

struct Stu
{
	char name[20];
	int age;
	float score;
};
int main()
{
	struct Stu s = { 0 };
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fscanf(pf, "%s %d %f", s.name, &s.age, &s.score);
	printf("%s %d %f", s.name, s.age, s.score);
	return 0;
}

结果
insert image description here


2.4 fread and fwrite

2.4.1fwrite

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
  1. The function of fwrite is to write a block of data to the stream. fwirte only works on files.
  2. The header file for fwirte is <stdio.h>. The first argument is a pointer to the array to be written to the stream, the second argument is the size of the array elements, the third argument is the number of array elements, and the fourth is a pointer to the output stream. Returns the total number of elements written to the stream if the output was successful. Returns 0 if both size and count are 0.

例子

struct Stu
{
	char name[20];
	int age;
	float score;
};
int main()
{
	FILE* pf = fopen("test.txt", "wb");//前面的函数读写文件都是文本信息,都可以看懂
	                                   //fread和fwrite读写文件都是二进制信息
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	struct Stu s = { "zhangsan",20,99.5 };
	fwrite(&s, sizeof(struct Stu), 1, pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here

2.4.2fread

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
  1. The function of fread is to read data from the stream and put it into a memory block. fread only works on files.
  2. The header file of fread is <stdio.h>. The first parameter is a pointer to an array whose size is at least size*count in order to store the data read from the stream, the second parameter is the size of the array elements, and the third parameter is the number of array elements , the fourth parameter is a pointer to the input stream. If the read is successful, the total number of read elements is returned. If the read fails or the end of the file is read, the respective indicators are set. These indicators can be used in conjunction with feror and feof to determine whether the read failed or read Get to the end of the file (will be mentioned later), if count or size is 0, then return 0.

例子

struct Stu
{
	char name[20];
	int age;
	float score;
};
int main()
{
	FILE* pf = fopen("test.txt", "rb");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	struct Stu s = { 0 };
	fread(&s, sizeof(struct Stu), 1, pf);
	printf("%s %d %f", s.name, s.age, s.score);
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here

2.5 Summary

Function Function name apply 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

2.6 Extension (sscanf and sprintf)

  1. scanf reads formatted data from the keyboard (input stream: keyboard stdin), and printf outputs data to the screen (output stream: screen stdout).
  2. fscanf formatted input for all input streams (input streams: stdin, open files), fprintf formatted output for all output streams (output streams: stdout, open files).
  3. sscanf restores a formatted data from a string, and sprintf stores the formatted data in a string.

例子

struct Stu
{
	char name[20];
	int age;
	float score;
};
int main()
{
	struct Stu s = { "zhangsan",18,99.5 };
	char buf[100] = { 0 };
	sprintf(buf, "%s %d %f", s.name, s.age, s.score);
	printf("%s\n", buf);
	printf("-------分割线---------\n");
	struct Stu tmp = { 0 };
	sscanf(buf, "%s %d %f", tmp.name, &tmp.age, &tmp.score);
	printf("%s %d %f", tmp.name, tmp.age, tmp.score);
	return 0;
}

结果
insert image description here


3. Random reading and writing of files

3.1fseek

int fseek ( FILE * stream, long int offset, int origin );
  1. The function of fseek is to reposition the position pointed by the position indicator in the stream. It locates the file pointer based on the position and offset of the file pointer.
  2. The header file is <stdio.h>. The first parameter is a pointer to the stream, the second parameter is the offset, and the third parameter is the starting position, which is the reference position of the offset. It has three fixed values: SEEK_SET (beginning of the file) , SEEK_CUR (the current position of the file pointer), SEEK_END (the end of the file). Returns zero on success, non-zero on failure.

例子

int main()
{
	FILE* pf = fopen("test.txt", "r");//先在文件内写好abcdef,现在用读的形式打开
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	//文件的顺序读写,读完一个字符后,文件指针指向下一个字符
	printf("%c\n", fgetc(pf));//a
	printf("%c\n", fgetc(pf));//b
	printf("%c\n", fgetc(pf));//c
	//按照顺序读写,接下来打印的是d,但我想要打印b
	fseek(pf, -2, SEEK_CUR);//当前位置是文件指针(位置指示器)指向d,后前偏移2就指向b
	printf("%c\n", fgetc(pf));
	//法2:	fseek(pf,1,SEEK_SET);从开头开始偏移
	//		printf("%c\n",fgetc(pf));
	//法3:	fseek(pf,-4,SEEK_END);//从末尾开始偏移
	//		printf("%c\n", fgetc(pf));
	fclose(pf);
	pf = NULL;
	return 0;
}

结果
insert image description here

3.2ftell

long int ftell ( FILE * stream );
  1. The function of ftell is to return the offset of the file pointer relative to the starting position.
  2. The header file is <stdio.h>, the parameter is a pointer to the stream, and the return value is the offset of the current file pointer relative to the starting position.

例子

int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	printf("%c\n", fgetc(pf));//a
	printf("%c\n", fgetc(pf));//b
	printf("%d\n", ftell(pf));
	return 0;
}

结果
insert image description here

3.3rewind

void rewind ( FILE * stream );
  1. The function of rewind is to return the position of the file pointer to the beginning of the file.
  2. The header file is <stdio.h>, the parameter is a pointer to the stream, and there is no return value.

例子

int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	printf("%c\n", fgetc(pf));//a
	printf("%c\n", fgetc(pf));//b
	printf("%d\n", ftell(pf));//2
	rewind(pf);
	printf("%c\n", fgetc(pf));//a
	return 0;
}

结果
insert image description here


4. Judgment of the end of file reading

4.1 Whether the file ends

  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 judges 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

4.2 feof and ferror

  1. 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 when the file reading ends, judging whether the reading fails to end, or the end of the file is encountered.
  2. feof returns true, indicating that the normal reading of the file ended when the end flag was encountered.
  3. ferror returns true, indicating that an error occurred during the reading process of the file, and it is over.

例子

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))
    puts("I/O error when reading");
  else if (feof(fp))
    puts("End of file reached successfully");
  fclose(fp);
}

Guess you like

Origin blog.csdn.net/Zhuang_N/article/details/128868881