File operation C language

file

For a program, the function we ultimately want to achieve is inseparable from the file. Its function is to save and read a series of data used and operated by the user. In general programs, we only use it to implement a certain function. After exiting, it is the past, and we can no longer find the traces and data used before. Just imagine if there is no mechanism to save some important data, what a terrible thing it would be. So how to read and write files? A series of file manipulation functions are given in the C language library to facilitate our operations.

First of all, we must be clear about the basic concepts of files:

1. The composition of the file

The file name consists of 3 parts:
file path + file name trunk + file suffix
For example: c:\TEXT\test.txt
For convenience, the file identifier is often called the file name.

2. File Type

Text file
binary file

File opening and closing

If you want to use a file, or store a set of data, then of course we need to find such a file, open it and perform write operations, and close it after completion to prevent misuse of it. The common opening and closing methods are as follows:

FILE * fopen ( const char * filename, const char * mode );
int fclose ( FILE * stream );

This is used by ANSIC. To open a file with fopen, it includes the first parameter, which is actually the path of the file; the second parameter is the opening behavior, such as reading "r" or writing "w", and Different ways for different functional requirements.
The following are the usage methods of some commonly used functions. When writing code, you can choose according to different needs;
Insert picture description herefor example, we want to open a file named code.txt in the TEXT folder of C drive and read it only. Operation, you can perform the following operations:

FILE* pf = fopen("C:\TEXT\code.txt", "r");

Guess you like

Origin blog.csdn.net/dream_i_success/article/details/110525347