Basis of documents

Basic knowledge of documents

What is a file?

This is very simple. We usually click the right mouse button and create a new folder. This is to create a file. For example, each folder in our disk is a file. We usually give a meaningful file name to prevent it from being found next time.

Why use files?

For example, when we write an address book code, we need to store data, but when you run out of the address book, you will close the address book. At this time, when you open the address book again, we will not find the last stored data, and when we have a file, we will save the last stored data. So the file makes the data persistent. When you use it next time, the last data still exists. (this refers to closing the address book instead of closing the whole project. Of course, all of them are gone.).

Document classification

We divide the program design into two files, one is the program file and the other is the data file.

Program files include source program files (suffix. c), object files (suffix. obj in windows Environment), and executable programs (suffix. 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 that outputs the content.

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

File pointer variable

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 of the declaration is FILE, which is named by the system
Generally, a FILE pointer is used to maintain the variables of the FILE structure, which is more convenient to use
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

Self summary: in other words, when we want to open a FILE, we will open a FILE information area in the memory. This FILE information area stores all kinds of information of the FILE (FILE name, FILE state, location, etc.) and we use a structure variable to store the information of these files. We use a pointer variable of FILE to maintain this FILE information area, We can access the FILE through this pointer variable.

Opening and closing of files

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.
Functions to open and close files

Open file fopen

Introduction to the use of fopen files (commonly used)

"r" is mainly to read the file. If it doesn't exist, there will be an error

”w "is mainly to write files. When there is no such file, it will create an empty file. If the file exists, it will empty the data in the file.

int main()
{
	FILE* pf = fopen("data.txt", "w");//In data Txt file, if there is no data at this time.
	                  //txt file will create a blank file and empty the file data if any
	if (pf == NULL) {
		printf("%s\n", strerror(errno));//If you fail to open the file, an error will be reported
		return;
	}
	fclose(pf);//Close file
	pf = NULL;
	return 0;
}

Close file fclose

Understanding of input and output

Output: output is to put the data in memory into a file.

Input: input is to put the file data input by keyboard and other input devices into memory.

Input and output functions in files

fputc character output function

fputc is to write characters into the stream or standard input. It should be added here that c language will open three streams by default, stdin standard input stream, stdout standard output stream and stderr standard error.

int main()
{
	FILE* pf = fopen("data.txt", "w");
	if (pf == NULL) {
		printf("%s\n", strerror(errno));
		return 0;
	}
	fputc('a', pf);
	fputc('b', pf);
	fputc('c', pf);
	fputc('d', pf);

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

Using fputc to input 26 English letters

int main()
{
	FILE* pf = fopen("data.txt", "w");
	if (pf == NULL) {
		printf("%s\n", strerror(errno));
		return 0;
	}
	char ch = 0;
	for (ch = 'a'; ch <= 'z'; ch++) {
		fputc(ch,pf);
	}
	fclose(pf);
	pf = NULL;
	return 0;
}

Of course, we can also go to the screen to change the pf stream into the standard output stream stdout of c language;

fgetc input character function

fputs output text line function

 

int main()
{
	FILE* pf = fopen("data.txt", "w");
	if (pf == NULL) {
		printf("%s\n", strerror(errno));
		return 0;
	}
	fputs("hello,world", pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

fgets input text line function

int main()
{
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL) {
		printf("%s\n", strerror(errno));
		return;
	}
	char buffer[1000] = { 0 };
	fgets(buffer, 1000, pf);
	printf("%s\n", buffer);
	fclose(pf);
	pf = NULL;
	return 0;
}

Read the file pointed to by pf and put it into the buffer,

Note that fgets reads only n-1 characters. For example, if the buffer size is 1000, it only reads 999 characters.

Print a file to another file

First, we need to open a file text Txt (this file needs to store the content to be copied to that file), and open a file in writing (text2.txt, we just want to copy the content in text.txt to text2.txt). After the copy operation, if we use the fgetc function to read text Txt file, and then read the file with fputc until EOF is returned, that is, there are no characters to read.

int main()
{
	//Put text Txt file to text2 Txt file
	//Read text Txt file
	FILE* pr = fopen("data.txt", "r");
	if (pr == NULL) {
		printf("%s", strerror(errno));
		return;
	}
	//Open text2 Txt file to write
	FILE* pw = fopen("data2.txt", "w");
	if (pw == NULL) {
		printf("%s\n", strerror(errno));
		//If pw fails to open the file, it indicates that pr is opened successfully. Here, close the pr file
		fclose(pr);
		pr = NULL;
		return;
	}
	//Copy file
	int ch = 0;
	//Here we need to read text line by line Txt file, and then write to text2 Txt file
	while ((ch = fgetc(pr)) != EOF) {
		fputc(ch, pw);
	}
	fclose(pr);
	pr = NULL;
	fclose(pw);
	pw = NULL;
	return 0;
}

fprintf is to read and format the standard input stream or the specified file stream. Similar to printf, it is also printing, that is, put the data to be printed into the specified file stream or standard output stream.

struct Stu
{
	char name[20];
	char sex[20];
	int age;
	int id;
};
int main()
{
	FILE* pf = fopen("text.txt", "w");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));
		return;
	}
	struct Stu s = { "Zhang San","male",18,20218769 };
	fprintf(pf,"%s %s %d %d", s.name, s.sex, s.age, s.id);

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

Here, for example, we need to read a structure data

struct Stu
{
	char name[20];
	char sex[20];
	int age;
	int id;
};
int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));
		return;
	}
	struct Stu tmp = { 0 };
	struct Stu s = { "Zhang San","male",18,20218769 };
	//fprintf(pf,"%s %s %d %d", s.name, s.sex, s.age, s.id);
	fscanf(pf,"%s %s %d %d", tmp.name, tmp.sex, &(tmp.age), &(tmp.id));
	printf("%s %s %d %d", tmp.name, tmp.sex, (tmp.age), (tmp.id));
	fclose(pf);
	pf = NULL;
	return 0;
}

Binary write and read

fread

struct Stu
{
	char name[20];
	char sex[20];
	int age;
	int id;
};
//Binary Reading
int main()
{
	struct Stu s = { "Zhang San","male",18,20218769 };
	FILE* pf = fopen("data4.txt", "rb");
	if (pf == NULL) {
		printf("%s\n", strerror(errno));
		return;
	}
	fread(&s, sizeof(struct Stu), 1, pf);
	printf("%s %s %d %d", s.name, s.sex, s.age, s.id);
	fclose(pf);
	pf = NULL;
	return 0;
}
fwrite

//Binary write
int main()
{
	struct Stu s = { "Zhang San","male",18,20218769 };
	FILE* pf = fopen("data4.txt", "wb");
	if (pf == NULL) {
		printf("%s\n", strerror(errno));
		return;
	}
	fwrite(&s, sizeof(struct Stu), 1, pf);
    fclose(pf);
    pf=NULL;
	return 0;
}

Compare scanf/fscanf/sscanf/printf/fprintf/sprintf

scanf and printf

scanf is a function that formats input from standard input

printf is a function that performs formatted output to the standard output stream

fscanf and fprintf

fscanf can read formatted data from standard input stream or specified input stream

fprintf can output the data to the standard input stream or formulate the output stream according to the format.

sscanf and sprintf

sscanf can extract formatted data from a string

sprintf converts a formatted data into a string.

Random reading of files

fseek

This function has seek respectively_ END,SEEK_ SET,SEEK_ CUR

SEEK_END is the position from the last character to the last one.

SEEK_SET is offset from the starting position, that is, the position of the first character

SEEK_CUR is the offset from the current character position

int main()
{
	//Random reading and writing of files
	FILE* pf = fopen("text.txt","r");
	int ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	//At this point, the file pointer should point to c
	fseek(pf, -2, SEEK_END);
	//fseek(pf, 2, SEEK_SET);
	//fseek(pf, 3, SEEK_CUR);
	ch = fgetc(pf);
	printf("%c\n", ch);

	//Close file
	fclose(pf);
	pf = NULL;
	return 0;
}

ftell function

int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (pf == NULL) 
	{
		printf("%s\n", strerror(errno));
		return;
	}
	//read file
	int ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	int ret = ftell(pf);
	printf("%d\n", ret);
	fclose(pf);
	pf = NULL;
	return 0;
}

rewind function

int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));
		return;
	}
		//read file
	int ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	int ret = ftell(pf);
	printf("%d\n", ret);
	rewind(pf);
	ret = ftell(pf);
	printf("%d\n", ret);
	fclose(pf);
	pf = NULL;
	return 0;
}

Distinguish between binary files and text files

Binary file refers to directly converting data into binary and putting it into memory.

The text file is converted into binary and put into memory by using ASCII code value.

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. The file stored in the form of ASCII characters is a text file.
How is a data stored in memory?
All characters are stored in ASCII form, and numerical data can be stored in ASCII form or binary form

Determination of the end of file reading

Keep in mind: in the process of file reading, the return value of feof function cannot be directly used to judge whether the file ends.
It is used to judge whether the reading fails or the end of the file is encountered when the file reading ends.

It should be noted here that feof is not used to determine whether the file is read, but to determine the reason for the end of the file, such as whether the file ends due to reading failure or the end of the file.

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 of reads

Keywords: C

Added by Lee-Bartlett on Thu, 24 Feb 2022 13:30:32 +0200