Introduction to file operation and C language implementation of address book management system 3.0 final version (file operation version)

1 Introduction

In the previous article, we learned the relevant knowledge points of dynamic memory development, and optimized our address book with dynamic memory functions, but there is still room for improvement in the address book. For example, under normal circumstances, the address book should be able to save contacts all the time Personal information, instead of being cleared after exiting, this requires us to actually save an address book.
Next, I will introduce you to files and how to use C language to manipulate files.

2. File operation

2.1 What is a file

Files on disk are files. But in programming, we generally talk about two kinds of files: program files, data files.
Program files: including source program files (suffix .c), object files (windows environment suffix . The environment suffix is ​​.exe).
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.
The file name consists of 3 parts: file path + file name trunk + file suffix
For example: c:\code\test.txt

This article is primarily concerned with data files.
In the past, the input and output of our data processing were all based on the terminal, that is, data was input from the keyboard of the terminal, and the running results were displayed on the monitor. In fact, sometimes we will output information to the disk, such as saving the address book, and then read the data from the disk to the memory for use when needed. Here, the files on the disk are processed.

2.2 File buffer

The ANSIC standard uses the "buffer file system" to process data files. The so-called buffer file system means that the system automatically creates a "file buffer" in the memory for each file being used in the program.
Data output from memory to disk will be sent to the buffer in memory first, and then sent to disk together after the buffer is filled.
If data is read from the disk to the computer, the data read from the disk file is input to the memory buffer (full of the buffer), and then the data is sent from the buffer to the program data area (program variables, etc.) one by one. The size of the buffer is determined by the C compilation system.

2.3 File pointer

In the cache file system, the key concept is "file type pointer", referred to as "file pointer".
Each used file has opened up a corresponding file information area in the memory, which is used to store the relevant information of the file (such as the name of the file, the status of the file and the current location of the file, etc.).
This information is stored in a structure variable. The structure type is declared by the system, and the name FILE
is generally maintained through a FILE pointer to maintain the variable
FILE* pf of this FILE structure;
define pf as a pointer variable pointing to FILE type data. You can make pf point to the file information area of ​​a certain file (it is a structure variable).
The file can be accessed through the information in the file information area. That is to say, the file associated with it can be found through the file pointer variable.

2.4 Opening and closing of files

Files should be opened before reading and writing, and should be closed after use.
Open:
FILE* fopen(const char* filename, const char* mode); mode is the way to open
Close:
int fclose(FILE* stream);

There are many ways to open files, here I will list them one by one for your reference:

文件使用方式               含义                    如果指定文件不存在
“r”(只读) 为了输入数据,打开一个已经存在的文本文件    出错
“w”(只写) 为了输出数据,打开一个文本文件             建立一个新的文件
“a”(追加) 向文本文件尾添加数据                       出错
“rb”(只读) 为了输入数据,打开一个二进制文件          出错
“wb”(只写) 为了输出数据,打开一个二进制文件          建立一个新的文件
“ab”(追加) 向一个二进制文件尾添加数据                出错
“r+”(读写) 为了读和写,打开一个文本文件              出错
“w+”(读写) 为了读和写,建议一个新的文件              建立一个新的文件
“a+”(读写) 打开一个文件,在文件尾进行读写            建立一个新的文件
“rb+”(读写) 为了读和写打开一个二进制文件             出错
“wb+”(读写) 为了读和写,新建一个新的二进制文件       建立一个新的文件
“ab+”(读写) 打开一个二进制文件,在文件尾进行读和写   建立一个新的文件

Example use:

int main()
{
    
    
	//打开文件
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return 1;
	}
	//写文件
	int ch = 0;
	fputc('w', pf);

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}


int main()
{
    
    
	//打开文件
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return 1;
	}
	//读文件
	int ch = 0;
	while ((ch = fgetc(pf)) != EOF)
	{
    
    
		printf("%c ", ch);
	}
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

2.5 Sequential reading and writing of files

Character input functions - fgetc - all input streams
Character output functions - fputc - all output streams
Text line input functions - fgets - all input streams
Text line output functions - fputs - all output streams
Format input functions - fscanf - all input stream
formatting output functions - fprintf - all output streams
binary input - fread - file
binary output - fwrite - file

3. Optimize address book

After introducing the file operation for everyone, we can use the file operation to optimize our address book, so that the address book can be saved to a file on the disk every time we exit, and it will be saved every time we restart. This file is then loaded into the address book, allowing us to print out all contacts directly.

3.1 Save address book

Use the file operation to save the information of the contacts in the address book in a txt file.

void SaveContact(const contact* pc)
{
    
    
	FILE* pf = fopen("contact.dat", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	int i = 0;
	for (i = 0; i < pc->count; i++)
	{
    
    
		fprintf(pf, "%s %s %d %s %s", pc->date->name, pc->date->sex, pc->date->age, pc->date->tele, pc->date->address);
	}
	fclose(pf);
	pf = NULL;
}

3.2 Load address book

We need to automatically load the contact information in the file every time we enter the program, so this function can be placed inside the function of initializing the address book.

void LoadContact(contact* pc)
{
    
    
	FILE* pf = fopen("contact.dat", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	people tmp = {
    
    0};
	while (fread(&tmp, sizeof(people), 1, pf))
	{
    
    
		CheckCapacity(pc);
		pc->date[pc->count] = tmp;
		pc->count++;
	}
	fclose(pf);
	pf = NULL;
}

In this way, we can permanently save the information of the contacts in the address book on the disk, and we can directly print the previously saved information whenever we open it.
Example 1

4. Ending

As of this article, the use of C language to implement the address book management system has been fully optimized. The main purpose is to learn various knowledge and optimize your own code through this small program. The idea is the most important thing. Thank you very much for your patience. Read, if you have any questions, you can leave a message in the comment area or send a private letter to the blogger. If you think the blogger wrote a good friend, you can support it three times, thank you.

Guess you like

Origin blog.csdn.net/qq_43188955/article/details/129976014