C language file operation (file reading and writing)


foreword

This article mainly introduces the relevant content of file operation in C language (for example: file reading, writing and other related functions).


1. Documents

We are almost inseparable from files in the use of computers. For example, common ones include word documents, txt text files, picture files, audio files, etc.

1. What is a document?

A file is a collection of information stored on a computer with a computer hard disk as a carrier. It is a kind of data source, and its main function is to save data.

In programming, we can divide files into two categories: program files and data files

(1) Program files

Including source program files (suffix .c), object files (windows environment suffix .obj), executable program files (windows environment suffix .exe).

(2) Data file

The content of the file is not necessarily the program, but the data read and written when the program is running, such as the file from which the program needs to read data, or the file that outputs the content.

2. File name

The file name is the identification of the existence of the file, and the operating system controls and manages it according to the file name. Each file is assigned a specific name consisting of the file's main name and extension.

That is: a file must have a unique file identifier for user identification and reference.
The file name contains three parts: file path + file name trunk + file suffix
Example: D:\Windows Kits\10\Lib\test.txt
insert image description here


2. File opening and closing

1. File pointer

We perform a series of operations on the file - open the file, close the file, write data to the file, and read data from the file. All operations are inseparable from the file pointer.

File pointer: FILE *
FILE : Each used file opens up a corresponding file information area in the memory, which is used to store the relevant information of the file (file name, file status and current location of the file, etc.). These information are stored in a structure variable named FILE.
FILE * : maintain the variable of this FILE structure through a FILE pointer, and operate on the file.

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

pf is a pointer variable pointing to FILE type data. That is, the file associated with it can be found through the file pointer variable.

2. File opening and closing

(1) fopen function
In C language, the file should be opened before operating the file. Use the fopen() function in the <stdio.h> header file to open the file. The usage is as follows:

//打开文件
FILE * fopen ( const char * filename, const char * mode );

The first parameter filename is the file name (including the file path), and the second parameter mode is the opening method. If the opening is successful, fopen returns a structure pointer address, otherwise returns NULL .

If no file path is specified, it defaults to the current working directory.
example:

//首先定义文件指针:fp
FILE *fp;
//用fopen()函数卡开文件, r——>以只读方式打开
fp = fopen("test.txt", "r"); //没有指定文件路径,则默认为当前工作目录。

(2) fclose function
After executing the file operation, use the fclose() function to perform the "close file" operation. In this way, related resources are released to avoid data loss. At the same time, it can also improve the overall execution efficiency of the system.
The usage of fclose() is: int fclose(FILE *fp);

//fp 为文件指针,关闭文件代码如下:
fclose(fp);

Close returns a value of 0 on success, otherwise returns a non-zero value.

Here's how the file is opened:

insert image description here
Example: Open W for writing only

#include <stdio.h>
int main()
{
    
    
    FILE* pf;
    //打开文件
    pf = fopen("file1.txt", "w");
    //创建文件并进行判断
    if (pf != NULL)
    {
    
    
    	printf("打开文件成功!");
        //关闭文件
        fclose(pf);
    }
    return 0;
}

insert image description here


3. Sequential reading and writing of files

After opening the file, you need to perform specific operations on the file. The following are the read and write functions of the file

Function Function name
character input function fgetc
character output function fputc
text line input function gets
text line output function fputs
format input function fscanf
format output function fprintf
binary input fread
binary output fwrite

example:

#include <stdio.h>
int main()
{
    
    
    FILE* fp;
    fp = fopen("D:\\codeFile\\test1.txt", "r");
    if (fp != NULL)
    {
    
    
        //feof(file stream )文件指针到达文件末尾
        while (!feof(fp)) //读文件
            printf("%c", fgetc(fp));
    }
    else
        printf("fail to open! \n");
    fclose(fp);
    return 0;
}

Result: ( the feof() function checks whether the file has been read )
insert image description here


Summarize

Tip: the above is the whole content of this article

Guess you like

Origin blog.csdn.net/m0_53689542/article/details/122779352