[C language] file operation function

Posted by Nicholas on Wed, 23 Feb 2022 05:38:06 +0100

[C language] file operation function

This article mainly studies the file operation functions * * fopen, fclose, fgetc, fgets, fputc, fputs, fwrite, fread, feof * *.

For the above functions, you need to import the header file stdio h

Why learn these functions? It must be because we need to store our data and put it into the hard disk for easy storage.

This article combs some of the most common file operation functions.

Preface: text files and binary files

According to the organization form of data, data files are called text files or binary files.

Data is stored in binary form in memory. If it is output to external memory without conversion, it is a binary file.

If it is required to store in the form of ASCII code on external memory, it needs to be converted before storage. Files stored in ASCII characters are text files

I Opening and closing of files

field name pointer

In the buffered file system, the key concept is "file type pointer", which is referred to as "file pointer".

Each used FILE opens up a corresponding FILE information area in the memory to store the relevant information of the FILE (such as the name of the FILE, the status of the FILE, the current location of the FILE, etc.). This information is stored in a structure variable. The structure type is declared by the system and named FILE

Creation of file pointer

FILE* pf

Definition PF is a pointer variable pointing to data of type FILE. You can make pf point to the FILE information area of a FILE (which 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.

II fopen and fclose

Fopen and fclose usually appear in pairs. With fopen, there will be fclose

fopen is the function to open the file and fclose is the function to close the file

Introduction to function parameters

//Open file
FILE * fopen ( const char * filename, const char * mode );

//Close file
fclose ( FILE * stream);

The first parameter of fopen indicates the file to be opened. If it is in this directory, write the file name directly. If it is not in this directory, write the absolute path of the file.

The second parameter of fopen indicates the operation form of files, which can be learned from the following figure.

fclose closes the file we opened.

example

After using the fopen function, you'd better judge whether the fopen file function returns NULL pointer.

int main()
{
	FILE* pr = fopen("data.txt", "r");//The first parameter is the file name I want to open, and the second parameter represents that the operation on the file is "read-only"
	if (NULL == pr)//Judge whether the pr file is opened successfully
	{
		printf("open for reading : %s", strerror(errno));
		return 0;
	}

	FILE* pw = fopen("data2.txt", "w");//The first parameter is the file name I want to open, and the second parameter represents that the operation on the file is "write"
	if (NULL == pw)//Judge whether the file is opened successfully
	{
		printf("open for writing : %s", strerror(errno));
		fclose(pr);//If opening this file fails, close the previous file.
		pr = NULL;
		return 0;
	}
    fclose(pr);//After using the file, close the file
    pr = NULL;//And set the file pointer to null
    fclose(pw);
    pw = NULL;
	return 0;
}

III fputc and fgetc

These two file functions have appeared in the code demonstration in the above case column. fgetc reads the characters in the file and fputc outputs the characters to the file.

//Function parameters of fgetc
int fgetc( FILE *stream );//stream represents the file that will read characters

//Function parameters of fputc
int fputc( int c, FILE *stream );// c represents the characters we will store, and stream is the file we store c.

example

This is a combination of the previous example.

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
	FILE* pr = fopen("data.txt", "r");//The first parameter is the file name I want to open, and the second parameter represents that the operation on the file is "read-only"
	if (NULL == pr)//Judge whether the pr file is opened successfully
	{
		printf("open for reading : %s", strerror(errno));
		return 0;
	}

	FILE* pw = fopen("data2.txt", "w");//The first parameter is the file name I want to open, and the second parameter represents that the operation on the file is "write"
	if (NULL == pw)//Judge whether the file is opened successfully
	{
		printf("open for writing : %s", strerror(errno));
		fclose(pr);//If opening this file fails, close the previous file.
		pr = NULL;
		return 0;
	}
	int ch = 0;
	while ((ch = fgetc(pr)) != EOF)//Write all the contents of the "data.txt" file into the "data2.txt" file
	{
		fputc(ch, pw);
	}
	return 0;
}

IV fgets and fputs

fgets is to read a line of data in the file. On the contrary, fputs is to output a line to the file.

Introduction to function parameters

//Function parameters of fgets
char *fgets( char *string, int n, FILE *stream );//The first parameter is the string we receive the data in the file. The second parameter n indicates how many characters we want to read, but the number of characters is (n-1) characters. The third parameter is the file we want to read.

//Function parameters of fputs
int fputs( const char *string, FILE *stream );//The parameters of this function are actually similar to fgetc, but the output here is a string into the file stream, not a character.

example

Input the data into the file and remind again that if the file is not in this directory, you need to add an absolute path

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
	FILE* pf = fopen("data.txt", "w");
	if (NULL == pf)
	{
		printf("open for write : %s", strerror(errno));
		return 0;
	}
	fputs("hello world\n", pf);
	fputs("haha\n", pf);

	fclose(pf);
	pf = NULL;
	return 0;
}

read file

int main()
{
	FILE* pf = fopen("data.txt", "r");
	if (NULL == pf)
	{
		printf("open for write : %s", strerror(errno));
		return 0;
	}
	char arr[2] = { 0 };//Open up two spaces to receive data
	fgets(arr, 13, pf);// fgets can only read (n-1) characters, so it is 13
	printf("%s", arr); 

	fgets(arr+1, 5 , pf);
	printf("%s", arr+1);


	fclose(pf);
	pf = NULL;
	return 0;
}

V fwrite and fread

fwrite is binary output, that is, output the content in binary form to a file for storage.

fread is the data saved in binary to read the file.

Introduction to function parameters

//fwrite function parameters
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );//The first parameter buffer indicates the address of the data we want to output, the second parameter size is the size of the data we want to output, the third parameter count is the number of data we want to input, and the fourth parameter is the file we want to input the data to.

//fread function parameters
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );//The first parameter buffer indicates the address of the data we want to receive, the second parameter size is the size of the data we want to receive, the third parameter count is the number of data we want to receive, and the fourth parameter is the file of the buffer we want to input the data into.

example

fwrite binary output

#include <stdio.h>
#include <errno.h>
#include <string.h>
struct Stu
{
	int age;
	char name[10];
	char id[20];
};
int main()
{
	struct Stu s[2] = { { 12, "zhangsan", "253534123" }, {13,"lisi","342342354"}};
	FILE* pr = fopen("date.txt", "wb");//wb means to open a binary file in order to output data
	if (NULL == pr)
	{
		printf("open for writing : %s", strerror(errno));
	}
	fwrite(&s, sizeof(struct Stu), 2, pr);

	fclose(pr);
	pr = NULL;
	return 0;
}

After operation:

Use fread to read date Data in TXT

#include <stdio.h>
#include <errno.h>
#include <string.h>
struct Stu
{
	int age;
	char name[10];
	char id[20];
};
int main()
{
	struct Stu s[2] = { 0 };//Open up two identical structure arrays to receive data
	FILE* pr = fopen("date.txt", "rb");
	if (NULL == pr)
	{
		printf("open for writing : %s", strerror(errno));
	}
	fread(s, sizeof(struct Stu), 2, pr);

	printf("%s %d %s\n", s[0].name, s[0].age, s[0].id);
	printf("%s %d %s\n", s[1].name, s[1].age, s[1].id);


	fclose(pr);
	pr = NULL;

	return 0;
}

File read succeeded

Vi feof

It is used to judge whether the reading fails or the end of the file is encountered when the file reading ends.

1. Whether the reading of text file is finished, and judge whether the return value is EOF (fgetc) or NULL (fgets)

For example:

fgetc determines whether it is EOF

fgets determines whether the return value is NULL

2. Judge the reading end of binary files, and judge whether the return value is less than the actual number to be read.

For example:

fread determines whether the return value is less than the actual number to be read.

example

Examples of text files

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int c; // Note: int, not char, requires EOF processing
    FILE* fp = fopen("test.txt", "r");
    if(!fp) {
        perror("File opening failed");
        return EXIT_FAILURE;
   }
 //fgetc will return EOF when reading fails or when the file ends
    while ((c = fgetc(fp)) != EOF) // Standard C I/O read file cycle
   { 
       putchar(c);
   }
    //Judge why it ended
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp))
        puts("End of file reached successfully");
    fclose(fp);
}

Examples of binary files

#include <stdio.h>
enum { SIZE = 5 };
int main(void) {
    double a[SIZE] = {1.,2.,3.,4.,5.};
    FILE *fp = fopen("test.bin", "wb"); // Binary mode must be used
    fwrite(a, sizeof *a, SIZE, fp); // Write array of double
    fclose(fp);
    double b[SIZE];
    fp = fopen("test.bin","rb");
    size_t ret_code = fread(b, sizeof *b, SIZE, fp); // Read the array of double
    if(ret_code == SIZE) {
        puts("Array read successfully, contents: ");
        for(int n = 0; n < SIZE; ++n) printf("%f ", b[n]);
        putchar('\n');
   } else { // error handling
       if (feof(fp))
          printf("Error reading test.bin: unexpected end of file\n");
       else if (ferror(fp)) {
           perror("Error reading test.bin");
       }
   }
    fclose(fp);
}

Topics: C Back-end