Beginner C language file operation

Test environment: WIN10 VS2019

Purpose of this chapter:

Let the reader understand how the C language reads and writes files, and can use some simple functions related to file operations.

File read and write operations

Here I have to clearly explain what is reading and writing files. This is very important to understand the reading and writing of files.

Read file : Put the data in the target file into the variable to be stored.

Write file : write the data in the variable to the target file.

file pointer

Baidu Encyclopedia: In the C language, a pointer variable is used to point to a file, and this pointer is called a file pointer. Various operations can be performed on the file pointed to by the file pointer.

The file pointer is of type FILE *

In order to make it easier for readers to understand this concept, I will give an example here.

If we want to read data from the file, the initial file pointer points to a. If we simply read the file data, we can only read a first, and then read b. If we point the file pointer to f, we can start reading data from f. (It can be easily understood like this)

file opening and closing

The file should be opened before reading and writing, and should be closed after the end of use.
When writing a program, when opening a file, it will return a FILE* pointer variable to point to the file, which is also equivalent to establishing the relationship between the pointer and the file. ANSIC stipulates that the fopen function is used to open the file and fclose to close the file.

About fopen:

We can use MSDN software or www.cplusplus.com to inquire about the usage of fopen

fopen has two parameters, the first is the filename of the file to open, and the second is the way to open the file

Note: If the first parameter does not take the file path and only writes the file name, the default path is in the directory of the source file. However, we usually bring the path, such as fopen("D:\\data.txt", "r"), and use double slashes when writing the path.

Open as follows:

How the file is used 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 data, open a text file create a new file
“A” (additional) Append data to the end of a text file create a new file
"rb" (read only) To enter data, open a binary file error
"wb" (write only) To output data, open a binary file create a new file
“Ab” (additional) Append data to the end of a binary file error
"r+" (read and write) Open a text file for reading and writing error
"w+" (read and write) For reading and writing, a new file is suggested 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 error
"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

 If you don't understand it, give a simple example.

int main()
{
	//以只读的方式打开文件
	FILE* pf = fopen("D:\\data.txt", "r");
	if (pf == NULL)
	{
		printf("%s", strerror(errno));
		return 0;
	}
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

I won't go into too much detail here. If you have any questions about the above code, please feel free to communicate with me, thank you.

About fclose:

To close the file, just pass the file pointer into the fclose function. It is a good practice to null this pointer after closing .

File operation related functions

The following basic functions can be queried from MSDN or www.cplusplus.com

Features 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
formatted output function fprintf all output streams
binary input fread document
binary output fwrite document

Use of fread()

 

The picture below represents the content of the initial file (binary file)

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<windows.h>
typedef struct student
{
	char ch[20];
	int age;
	int id;
}stu;
int main()
{
	//打开文件
	FILE* pf = fopen("D:\\data.txt", "rb");
	if (pf == NULL)
	{
		printf("%s", strerror(errno));
		return 0;
	}
	//读数据
	stu arr[2] = { 0 };
	fread(arr,sizeof(stu),2,pf);
	printf("%s %d %d", arr[0].ch, arr[0].age, arr[0].id);
	printf("\n%s %d %d", arr[1].ch, arr[1].age, arr[1].id);

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

operation result:

 fwrite() uses

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<windows.h>
typedef struct student
{
	char ch[20];
	int age;
	int id;
}stu;
int main()
{
	//打开文件
	FILE* pf = fopen("D:\\data.txt", "wb");
	if (pf == NULL)
	{
		printf("%s", strerror(errno));
		return 0;
	}
	//写数据
	stu arr[2] = { {"张三",20,2021},{"王五",21,2022}};
	fwrite(arr,sizeof(stu),2,pf);
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

 Write result:

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 opens up a "file buffer" in 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 the disk after the buffer is full. If the data is read from the disk to the computer, the data is read from the disk file and input into the memory buffer (full buffer), and then the data is sent to the program data area (program variables, etc.) from the buffer one by one. The size of the buffer is determined by the C compilation system.

#include <stdio.h>
#include <windows.h>
//VS2013 WIN10环境测试
int main()
{
FILE*pf = fopen("test.txt", "w");
fputs("abcdef", pf);//先将代码放在输出缓冲区
Sleep(10000);
fflush(pf);//刷新缓冲区时,才将输出缓冲区的数据写到文件(磁盘)
//注:fflush 在高版本的VS上不能使用了
fclose(pf);
//注:fclose在关闭文件的时候,也会刷新缓冲区
pf = NULL;
return 0;
} 

//Note: fclose also flushes the buffer when closing the file

A conclusion can be drawn here:
because of the existence of the buffer, when the C language operates the file, it needs to flush the buffer or close the file when the file operation ends. Failure to do so may cause problems reading and writing files.

Summarize

For beginners, it doesn't matter if you can't remember many functions related to file operations, just check MSDN more.

It is strongly recommended to use the functions related to file operations mentioned in this chapter.

At last

If you have any questions about this chapter, please feel free to communicate with me.

If there is an error in this chapter, please point it out, I am very grateful.

If you find it useful, please like and comment, thank you.

Guess you like

Origin blog.csdn.net/m0_62171658/article/details/123077960