Detailed explanation of various operations on files

Table of contents

1. What is a stream?

2. File opening and closing

1. Know fopen and fclose

2. Different opening methods

3. Use fopen and fclose

3. File read and write operations

1. fgetc and fputc

1.1 Understanding fgetc and fputc

1.2 Using fgetc and fputc

2. fgets and fputs

2.1 Understanding fgets and fputs

2.2 Using fgets and fputs

3. fread and fwrite

3.1 Understanding fread and fwrite

3.2 Using fread and fwrite

4. fscanf and fprintf

4.1 Understanding fscanf and fprintf

4.2 Using fscanf and fprintf

4. What is input and output?

5. Random reading and writing of files

1. fseek function

1.1 Know the fseek function

1.2 Using the fseek function

2. ftell function

2.1 Know the ftell function

2.2 Using the ftell function

3.rewind

3.1 Understanding the rewind function

3.2 Using the rewind function


1. What is a stream?

Before we talk about it, we have to first talk about the stream (stream in English) . The process of reading data from the device into the memory and writing data from the memory to the disk is very similar to the flow of data, so this process is called "visually". "Stream"    We usually use the standard input stream when we use scanf to assign values ​​to the variables in the program, and the standard output stream is used when printing the content to the screen through printf. In the c language, once the program is running It will automatically open three streams for you, standard input stream (stdin), standard output stream (stdout) and standard error stream (stderr),    so there is never such an operation as opening or closing the keyboard. But when the program is compiled, it can't know what file you want to open, so we need to open the required file by ourselves and close it after use.

2. File opening and closing

1. Know fopen and fclose

Function definitions are taken from cplusplus.com - The C++ Resources Network 

 

The function of the fopen function is to open the file . It has two parameters, both of which are pointers to unmodifiable character pointers. When using it, the first parameter passed is the name of the file, and the second parameter is the open file. The way. The value it returns is the address where you opened the file. It returns a null pointer (NULL) if the file fails to open.

The function of the fclose function is to close the file , and the parameter is a file pointer. When passing the parameter, just pass the address of the file you want to close (the address obtained through the fopen function)    (in fact, the essence is to pass the corresponding stream, But this is too abstract) It will help you close the file, if the close is successful, it will return 0, otherwise return EOF (-1)

2. Different opening methods

 Taken from Bit Employment Class

3. Use fopen and fclose

#include<stdio.h>
int main()
{
	FILE*a=fopen("abcd.txt", "r");
	//以只读的方式打开当前目录下名叫abcd.txt的文件
    //并通过文件指针a接收地址
	if (a == NULL)
	{
		perror("fopen");//错误提示
	}
	fclose(a);//将打开的文件关闭
	a = NULL;//将野指针置为空指针
}

 There is no file called abcd.txt in my folder now. In other words, opening this time is doomed to fail, let’s try it

 Sure enough, it failed. Next, let’s try to open the file with the mode of w , because the mode of w will also create a file when the file does not exist.

#include<stdio.h>
int main()
{
	FILE*a=fopen("abcd.txt", "w");
	//以只写的方式打开当前目录下名叫abcd.txt的文件
    //并通过文件指针a接收地址
	if (a == NULL)
	{
		perror("fopen");//错误提示
	}
	fclose(a);//将打开的文件关闭
	a = NULL;//将野指针置为空指针
}

There is no problem with the operation. Next, let us see if such a file called abcd.txt has been created in the directory.

 Sure enough, it was created. This is not magic, nor is it directed by the author. This is what happened in real life, and it was created through our program.

3. File read and write operations

1. fgetc and fputc

1.1 Understanding fgetc and fputc

The function of fgetc is to fetch characters from the corresponding stream and return the ASCII value of the corresponding character. If the reading fails, EOF will be returned. fputc will pass the given character into the corresponding stream. If the character is successfully obtained, then Its return value is the corresponding character.

1.2 Using fgetc and fputc

Before using fgetc, we first use fputc to write a character into a file, so that we can use fgets to read characters from a non-empty file.

#include<stdio.h>
int main()
{
	FILE* pf=fopen("abcd.txt","w");
	//以只写的方式打开一个叫abcd.txt的文件如果文件不存在则创建该文件
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputc('a',pf);
	//将字符a放进名字叫abcd.txt的文件中
    fclose(pf);
    pf=NULL;
}

 

 It can be seen that there is nothing in the abcd.txt file before running the program, let us run it

After running, the a character is indeed written into the file abcd.txt.

Then let's try fgetc, try to get the character out of the stream, and assign it to a variable in the program. It should be noted that fgetc will automatically point the pointer of the file to the next character after reading the character. Characters    We can demonstrate it through code. The meaning of this string of codes is to read four characters from the content of the file pointer pointed to by pf and print them out in sequence. For this reason, we first write some characters in the abcd.txt file, so as not to read less than four characters

 

code show as below: 

#include<stdio.h>
int main()
{
	FILE* pf = fopen("abcd.txt", "r");
	//以只读的方式打开一个叫abcd.txt的文件
	//如果文件不存在则报错
	if (pf == NULL)
	{
		perror("fopen");//错误警告
		return 1;
	}
	char ch=fgetc(pf);
	//从pf所指向的流(文件)中读取一个字符并赋给ch
	//要注意的是,当fgetc读取完字符后它会自动地将文件指针指向文件中的下一个字符
	//也就是说,你在下一次读取字符的时候会直接读到下一个字符
	printf("%c\n", ch);
	//将ch从流中读取的数据打印出来
	ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	fclose(pf);//关闭文件
	pf = NULL;//将野指针置为空指针
}

The result of the operation is as follows:

Sure enough, 4 characters were read in sequence. 

2. fgets and fputs

2.1 Understanding fgets and fputs

The function of fgets is to read the string from the stream and store it in the specified character array.     It has three parameters, the first is the variable used to store the string read from the stream, and the second parameter The meaning of num means that only num-1 characters can be extracted from it at most. Here I think it is because the fgets function will automatically add '\0' after the obtained character, because if there is no '\0', this is also It cannot be called a string, and it will print out a series of random values ​​​​during the printing process until it encounters '\0' and will not stop. So counting '\0' is to take out a string of num size. The third parameter is the corresponding stream, where you want to get the data from, just pass the stream there. The value type returned by fgets is a character pointer. If the string is passed successfully, it will return the address of str, and if it fails, it will return NULL.

The function of fputs is to put the string into the corresponding stream.     Its parameters are very simple and only two, one is the address of the string you want to put in, and the other is the stream to be put in. If fputs successfully writes data, it The return value is a positive number, or a negative number if the write fails.

2.2 Using fgets and fputs

In the same way, we first use fputs to store a string in the file, and the file has been emptied before storing.

code show as below: 

#include<stdio.h>
int main()
{
	FILE* pf = fopen("abcd.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputs("今天天气真好", pf);
	//将这个字符串写进abcd.txt中
	fclose(pf);
	pf = NULL;
}

The result of the operation is as follows: 

 Since a Chinese character occupies two bytes, it is not easy to display fgets, so we randomly store some letters in this file, and take them out through fgets, store I am a student in abcd.txt, and use fgets to get 6 from it character (not counting '\0'), and print it

 The result of the operation is as follows:

It is true that six characters are taken out, many x are written to str, and  '\0' is indeed stored in it through monitoring observation.

3. fread and fwrite

3.1 Understanding fread and fwrite

 

The function of fread is to read count content of size size from the stream in binary form and store the content in ptr.

The function of fwrite is to take out count size content from ptr in binary form and put it into the corresponding stream.

3.2 Using fread and fwrite

In the same way, first use fwrite to modify the content of the file, there is no content in the file

code show as below: 

#include<stdio.h>
struct abc
{
	int a;
	float b;
};//创建一个名字为struct abc类型的结构体
int main()
{
	FILE* pf = fopen("abcd.txt","wb");
	if (pf == NULL)
	{
		perror("fopen");
		//错误警告
		return 1;
	}
	struct abc a1 = { 100,3.14f };
	fwrite(&a1,sizeof(struct abc),1,pf);
	//将1个大小为struct abc的写进pf中
	fclose(pf);//关闭文件
	pf = NULL;//将野指针置为空指针
}

Run the program, the result is as follows:

Let me go, what is this, what is this, I don’t understand, aren’t we saving 100 and 3.14? Don't make a fuss, the reason why you can't understand it is because the information we store is binary information, and we store the information in the file abcd.txt in binary form.

Use fread to read data in binary form, the content in the file is still the binary data stored before

 code show as below:

#include<stdio.h>
struct abc
{
	int a;
	float b;
};//创建一个名字为struct abc类型的结构体
int main()
{
	FILE* pf = fopen("abcd.txt", "rb");
	//以二进制只读的方式打开一个名为abcd.txt的文件
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	struct abc a1 = {0};
	fread(&a1, sizeof(struct abc), 1, pf);
	//以二进制的方式将1个大小为struct abc的内容从pf所指向的指针内容中取出,放在a1这个结构体中
	printf("%d %f", a1.a, a1.b);
	//将内容打印出来
	fclose(pf);
	pf = NULL;
}

The result of the operation is as follows: 

 fread successfully converts the binary information into what we need.

4. fscanf and fprintf

4.1 Understanding fscanf and fprintf

 

 The function of fscanf is to input the data in the stream into the program in the form of a format. It has a variable as a stream, and the other with ... means that the number of parameters is variable. The scanf and printf functions also have parameters. innumerable.

The function of fprintf is to output the data in the program to the stream in a format, and the variables are consistent with fscanf.

4.2 Using fscanf and fprintf

The use of fscanf and fprintf is very similar to that of scanf and printf. It can be seen from the variables, but there is an additional stream form. But I can tell you this, what scanf and printf can do, fscanf and fprintf It can also be done, but what fscanf and fprintf can do scanf and printf may not be able to do    because scanf and printf only apply to standard input stream and standard output stream. While fscanf and fprintf can be applied to all input streams and all output streams.

 

 Above code:

As usual, we still use fprintf to output the contents of the program to a file, and the file is still empty

 code show as below:

#include<stdio.h>
int main()
{
	FILE* pf = fopen("abcd.txt", "w");
   //以只写的方式打开abcd.txt
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	int a = 3; int b = 10;
	fprintf(pf,"%d %d",a,b);
	//将a,b以int的方式输入到pf所指向的文件中
	fclose(pf);
	pf = NULL;
}

operation result:

Use fwrite to take out the content in the stream and modify the variables in the program. 

The content of the file is as follows:

code show as below:

#include<stdio.h>
int main()
{
	FILE* pf = fopen("abcd.txt", "r");
	//以只读的方式打开abcd.txt
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	int a = 0; int b = 0;
	fscanf(pf, "%d %d", &a, &b);
	//将pf所指向的文件的内容以整型的方式输入到a,b中
	printf("a的值为%d\nb的值为%d", a,b);
	fclose(pf);
	pf = NULL;
}

 The result of the operation is as follows:

 

4. What is input and output?

Some friends will feel uncomfortable because of the problem of input and output, and cannot understand it at all. Here, the author will describe in detail what is the real input and output.

In the eyes of many people, input and output are limited to printing on the screen as output, and writing on the keyboard is input. This is a superficial understanding. In our opinion, the function of scanf is to modify the variables in the program through the keyboard, which is input. The function of printf is to print out what we want, which is output. The function of gets is to read the string from the keyboard, which is input. The function of puts is to print the string on the screen, which is output. These understandings are not wrong, but most people who understand this way will mistakenly think that writing is input and printing is output, which is too one-sided. In our c language programming, input and output are relative to the program. I send things to the outside (such as the screen) through the program called output, and I use external things (such as inputting characters through the keyboard) to input things to the program. This is called input     . It is the real meaning of input and output. To give another example, I send data to the file through the program, which is called output (instead of the input you understand). I send the content of the file to the program by reading and writing. Input ( Rather than the output you understand), and finally emphasize again, the input and output are viewed from the perspective of the program.

5. Random reading and writing of files

1. fseek function

1.1 Know the fseek function

 The function of the fseek function is to move the stream to the position you want. There are three parameters, one is the stream, one represents the offset you want, and the other represents where you want to start the offset. Only you know Where do you start to offset before you can know how much the offset is, and how to offset to the desired position. The return type is an integer, and it will return 0 when fseek is used normally, and a non-zero value if an error occurs.

 There are three kinds of offset positions. SEEK_SET means to offset from the beginning of the file, and SEEK_CUR means to offset from the current stream position. For example, I used fgetc to successfully fetch two files from one file. Character, at this time, take one when the offset is 0, and take another one when the offset is 1, so the pointer points to the position where the offset is 2 at this time. When I use SEEK_CUE at this time, I will directly offset from this position of the file. The meaning of SEEK_END is to start the offset from the end of the file (referring to the offset from the last character)

1.2 Using the fseek function

Store a string of letters in a file

 code show as below:

#include<stdio.h>
int main()
{
	FILE* pf = fopen("abcd.txt", "r");
	//以只读的方式打开abcd.txt
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fseek(pf,3,SEEK_SET);
	char ch=fgetc(pf);
	//从pf所指向的文件开头偏移3的位置处取一个字符出来,并赋给ch
	printf("%c", ch);
	fclose(pf);
	pf = NULL;
}

The result of the operation is as follows: 

 Sure enough, the letter d with an offset of 3 was taken out

2. ftell function

2.1 Know the ftell function

The function of the ftell function is very simple, it is to tell you what is the offset relative to the initial file position at this time

2.2 Using the ftell function

put a string of letters in the file 

 code show as below:

#include<stdio.h>
int main()
{
	FILE* pf = fopen("abcd.txt", "r");
	//以只读的方式打开abcd.txt
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fseek(pf,-5,SEEK_END);
	//将指针从文件最后一个字符偏移-5
	char ch = fgetc(pf);
	//取一个字符,偏移+1,偏移相对最后一个字符为-4
	//根据文件内容可知此时偏移量为7
	int a = ftell(pf);
	printf("偏移量为%d的字符为%c\n",a,ch);
	fseek(pf, 2, SEEK_CUR);
	//将指针从文件当前位置偏移2
	ch = fgetc(pf);
	//取一个字符,偏移+1
	//故此时偏移量为10
	a = ftell(pf);
	printf("偏移量为%d的字符为%c\n", a, ch);
	
	fclose(pf);
	pf = NULL;
}

The result of the operation is as follows: 

 consistent with our analysis.

3.rewind

3.1 Understanding the rewind function

What it does is set the position of the stream to the beginning 

3.2 Using the rewind function

Still use the contents of the previous file

code show as below:

#include<stdio.h>
int main()
{
	FILE* pf = fopen("abcd.txt", "r");
	//以只读的方式打开abcd.txt
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fseek(pf,-5,SEEK_END);
	//将指针从文件最后一个字符偏移-5
	char ch = fgetc(pf);
	//取一个字符,偏移+1,偏移相对最后一个字符为-4
	//根据文件内容可知此时偏移量为7
	int a = ftell(pf);
	printf("偏移量为%d的字符为%c\n",a,ch);
	fseek(pf, 2, SEEK_CUR);
	//将指针从文件当前位置偏移2
	ch = fgetc(pf);
	//取一个字符,偏移+1
	//故此时偏移量为10
	a = ftell(pf);
	printf("偏移量为%d的字符为%c\n", a, ch);
	rewind(pf);//将位置设置为开头
	ch=fgetc(pf);//从开头取一个字符给ch
	printf("%c\n",ch);
	fclose(pf);
	pf = NULL;
}

 The result of the operation is as follows:

Judging from the results, the rewind function does indeed set the position of the stream to the beginning.

Today's sharing is over here, thank you for your visit, I wish you a bright future O(∩_∩)O

Guess you like

Origin blog.csdn.net/fq157856469/article/details/131816282