c language file operation

Keywords: C

1. Why use files

Our general data persistence methods include storing data in disk files, databases, etc. Using files, we can store the data directly on the hard disk of the computer, so as to achieve the persistence of the data.

2. What is a document

Files on disk are files. But in programming, we generally talk about two kinds of files: program files and data files (classified from the perspective of file function)
2.1 procedure documents
It includes source program files (suffix. c), object files (suffix. obj in windows Environment), and executable programs (suffix. exe in windows Environment).
2.2 data files
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 that outputs the content.
2.3 file name
A file should have a unique file ID so that users can identify and reference it.
The file name consists of three parts: file path + file name trunk + file suffix
For example: c:\code\test.txt
For convenience, the file ID is often referred to as the file name

3. Opening and closing of files

3.1 document 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
For example, the stdio.h header file provided by VS2013 compilation environment has the following file type declaration

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 in it. Users don't have to care about the details. Generally, the variables of the FILE structure are maintained through a FILE pointer, which is more convenient to use.

FILE* pf;      File pointer variable

3.2 opening and closing of documents

The file should be opened before reading and writing, and closed after use.

When writing a program, when opening a FILE, a pointer variable of FILE * will be returned to point to the FILE, which is equivalent to establishing the relationship between the pointer and the FILE.

If fopen is, but there is no fclose, file resource disclosure may be triggered. There is an upper limit to the number of times a file can be opened.

There are three files that are automatically opened by the operating system when starting the program.

These three files are called:
stdin: standard input (keyboard)
stdout: standard output (display)
stderr: standard error (display)

printf is actually writing data to the standard output. The standard output file corresponds to the hardware device of the display, not the disk file
scanf is actually reading data from standard input. The standard input file corresponds to the hardware device of the keyboard, not the disk file.

Open file
FILE * fopen (const char *filename, const char *mode );
Close file
int fclose ( FILE * stream );
File usagemeaningIf the specified file does not exist
"r" (read only)To enter data, open an existing text fileerror
"w" (write only)To output data, open a text file, empty the original data, and write from scratchCreate a new file
"a" (added)Add data to the end of a text fileerror
"rb" (read only)To enter data, open a binary fileerror
"wb" (write only)In order to output data, open a binary file, empty the original data and write from scratchCreate a new file
"ab" (additional)Add data to the end of a binary fileerror
"r +" (read / write)To read and write, open a text fileerror
"w +" (read / write)In order to read and write, it is recommended to create a new file, empty the original data and write from scratchCreate a new file
"a +" (read / write)Open a file and read and write at the end of the fileCreate a new file
"rb +" (read / write)Open a binary file for reading and writingerror
"wb +" (read / write)To read and write, create a new binary file, empty the original data, and write from scratchCreate a new file
"ab +" (read / write)Open a binary file and read and write at the end of the fileCreate a new file
int main() {
	FILE *fp = fopen("file.txt", "w");
	if (fp == NULL) {
		perror("fopen");
		return;
	}
	fclose(fp);
}

Generate files in the project path

4. Sequential reading and writing of documents

functionFunction nameApply to
Character input functionfgetcAll input streams
Character output functionfputcAll output streams
Text line input functionfgetsAll input streams
Text line output functionfputsAll output streams
Format input functionfscanfAll input streams
Format output functionfwriteAll output streams
Binary inputfreadtext
Binary outputfwritetext

fgetc gets a character

int fgetc ( FILE * stream );

The following code function is to read the number of characters in the file

FILE* fp = fopen("test.txt", "r");
	if (fp == NULL) {
		perror("fopen");
		return;
	}
	int c=0;
	int n = 0;
	do {
		c = fgetc(fp);
		n++;
	} while (c != EOF);
	printf("%d\n",n);
	fclose(fp);

fputc outputs one character

int fputc ( int character, FILE * stream );
char c;
	FILE * pf= fopen("text.txt", "w");
	if (pf != NULL) {

		for (c = 'A'; c <= 'Z'; c++)
			fputc(c, pf);

		fclose(pf);
	}

fgets gets a string
Read num characters from the FILE pointed to by FILE * and store them in the string str
num: maximum number of characters to copy into str (including terminated null characters)

char * fgets ( char * str, int num, FILE * stream );

FILE* fp = fopen("test.txt", "r");
	if (fp == NULL) {
		perror("fopen");
		return;
	}
	char s[5] = { 0 };
	fgets(s, 5, fp);
	printf(s);
	fclose(fp);

fp points to the hello world saved in the file and reads 5 characters (including empty characters)

fputs outputs a string
Write str string to the FILE pointed to by FILE *

int fputs ( const char * str, FILE * stream );
FILE* fp = fopen("test.txt", "w");
	if (fp == NULL) {
		perror("fopen");
		return;
	}
	char *s = "hello world";
	fputs(s,fp);
	fclose(fp);


The fread function reads binary files

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Reading a file is actually copying the data from the disk to memory

void *ptr refers to the memory space used to store data copied from disk
Size represents the size bytes of each element
count indicates how many elements to copy
size * count is the total bytes read
FILE * use it to find the location of the corresponding FILE on the disk
size_t returns the number of elements actually read

FILE *fp = fopen("test.txt", "r");
	if (NULL == fp) {
		perror("fopen");
		return;
	}
	char buffer[1024] = { 0 };
	size_t n = fread(buffer, 1, 100, fp);
	printf("n=%d \n", n);
	printf("%s\n", buffer);

	fclose(fp);


The modification code is as follows:

size_t n = fread(buffer, 2, 100, fp);


The frwrite function writes a binary file

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

To write a file is to copy the data in memory to a file

void *ptr points to memory
Size indicates the size of each element in bytes
How many elements are there in count
FILE * indicates the return value of fopen, which is used to find the location of the corresponding FILE on the disk
size_t returns the number of actually written elements. The number of actually successful elements may be less than count, mainly because the disk is full

fswrite format write

int fprintf ( FILE * stream, const char * format, ... );
FILE *fp = fopen("test.txt", "w");
	if (NULL == fp) {
		perror("fopen");
		return;
	}
    fprintf(fp,"name: %s  age: %d", "lili",20);
	fclose(fp)

stdout is a variable of FILE * type, which is the standard output just mentioned. It is output on the display

fprintf(stdout, "num= %d\n", 10);    similar printf

fscanf format read

int fscanf ( FILE * stream, const char * format, ... );
int age = 0;
	char name[32] = { 0 };
	FILE *fp = fopen("test.txt", "r");
	if (NULL == fp) {
		perror("fopen");
		return;
	}
	fscanf(fp, "name: %s  age: %d", name, &age);
	printf("%s  %d\n", name, age);
	fclose(fp);

     int num = 0;
	printf("%d\n", num);
	fscanf(stdin, "%d", &num);    similar scanf
	printf("%d\n", num);


sscanf parses a function from a string

    char *s = "num = 10";
	int num = 0;
	sscanf(s, "num = %d", &num);
	printf("%d\n", num);


sprintf outputs a formatted result to a string

char s[32] = { 0 };
	sprintf(s, "num = %d\n", 10);
	printf("%s\n", s);

Posted by Pintonite on Wed, 10 Nov 2021 17:39:12 -0800