In-depth understanding of file operations - C(1)

Why use files

The address book written earlier, the data will disappear after adding the number of people and exiting the program. At this time, the data is stored in the memory. The next time the address book program is run, the data has to be re-entered. It is very uncomfortable to use such an address book.

So file operations came into being.
There are two ways to persist data: 1. Store data in disk files 2. Store in database
Using files, we can store data directly on the hard disk of the computer, thus achieving data persistence.

what is a file

But in programming, we generally talk about two kinds of files: program files and data files (classified from the perspective of file functions).

Program files : including source program files (suffixed with .c), object files (suffixed with .obj in windows environment), and executable programs (suffixed with .exe in windows environment).

Data file : The content of the file is not necessarily the program, but the data read and written when the program runs, such as the file from which the program needs to read data, or the file from which the content is output.

The input and output of the data processed in the previous chapters are all based on the terminal, that is, the data is input from the keyboard of the terminal, and the operation result is displayed on the display.

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, and the file on the disk is processed here.

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 identifier is often referred to as the file name.

Some concepts about files

File pointer : In the buffer file system, the key concept is " 文件类型指针", referred to as "file pointer".

File information area : Each used file has 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 systematically and named FILE .

The stdio.h header file provided by the VS2013 compilation environment has the following file type declarations;

struct _iobuf {
    
    
        char *_ptr;
        int   _cnt;
        char *_base;
        int   _flag;
        int   _file;
        int   _charbuf;
        int   _bufsiz;
        char *_tmpfname;
       };
typedef struct _iobuf FILE;

Whenever a file is opened, the system will automatically create a variable of FILE structure according to the situation of the file , and fill in the information, the user does not need to care about the details.

FILE pointer : Generally, the variables of the FILE structure are maintained through a FILE pointer, which is more convenient to use.

Next we can create a pointer variable of FILE*:

FILE* pf;//文件指针变量

Define pf to be a pointer variable to data of type FILE. You can make pf point to the file information area of ​​a file (it is a structure variable). The file can be accessed through the information in the file information area. That is, the file associated with it can be found through the file pointer variable

insert image description here

Provisions : The file should be opened before reading and writing , and the file 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

First understand what it means to read and write.
Write file : output to a file or screen.
Read file : input into memory.
insert image description here

file function

fopen

Function prototype :

FILE *fopen( const char *filename, const char *mode );

Function :
Open a file.
The function of this function is to open a file. The first parameter of the function is the file name of the file you want to open , and the second parameter is the form of opening the file.

Return value : Each of these functions returns a pointer to the open file. A null pointer value indicates an error.
Returns a pointer to the file, or a null pointer if the open error occurs.
Note: The validity of the return value of fopen needs to be checked

	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return;//失败返回
	}

fclose

Function prototype :

int fclose( FILE *stream );

function

Closes a stream (fclose) .
Closes a stream

Return value
fclose returns 0 if the stream is successfully closed. return EOF to indicate an error
return 0 if the stream is closed successfully, return EOF(-1) if failed.

example code

	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return 1;//失败返回
	}

absolute path

The absolute path is the location of the specific file.
E.g:

D:\c-language\c yuyan\c yuyan\data.txt

FILE* pf = fopen("D:\\c-language\\c yuyan\\c yuyan\data.txt", "r");

But in order to prevent the '\' and the following characters in the string from being regarded as escape characters as a whole, it is necessary to add a '\' after each '\'.

How the file is opened

The first three are commonly used methods.
rule:

file open method meaning
"r" (read only) Open the file for input. If it does not exist, an error will be reported.
"w" (write only) To output data, open a text file. If it exists, clear the data in it and output it. A new file will be created if it does not exist.
"a" (append) Append data to the end of a text file. Create the file if it does not exist.
"rb" (read only) To enter data, open a binary file. If it does not exist, an error occurs.
"wb" (write only) To output data, open a binary file. If it does not exist, create a new file.
“Ab” (additional) Append data to the end of a binary file. If it does not exist, an error occurs.
"r+" (read and write) Open a file for updating (input and output). Error if not present.
"w+" (read and write) Create an empty file and open it for updating (input and output). If a file with the same name already exists, its contents will be discarded and the file will be treated as a new empty file.
"a+" (read and write) Open a file for reading and writing at the end of the file. Create a new file if it does not exist.

file operation process

The following is the general flow of file operations.

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
    
    
	//打开文件
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return 0;
	}
	//对文件进行一系列操作
	......
	.....
	//关闭文件
	fclose(pf);
	pf = NULL;置空
	return 0;
}

Guess you like

Origin blog.csdn.net/qq2466200050/article/details/123692752