The article in this chapter is mainly about file teaching. You may be a little unfamiliar with the file in C language. These two things seem to be completely irrelevant, but in fact they have many connections. This article will explain some The effect of opening and closing the file and using it with some library functions, let us learn
why use files
When we write a program, every time we run it, the data in it may not exist. When we want to see this content, we need to re-run it, just like the address book we wrote. We enter the data Sometimes, when we open it again, the previous data is no longer there, so we have to implement something that can record information, that is, the file
Data ceases to exist only when we choose to delete it ourselves. This involves the problem of data persistence. Our general data persistence methods include storing data in disk files and storing them in databases.
Using files, we can store data directly on the hard disk of the computer, achieving data persistence.
What is a document?
Files on disk are files.
But in program design, we generally talk about two types of files: program files and data files (classified from the perspective of file functions).
program files
Including source program file (suffix .c), object file (windows environment suffix .obj), executable program (windows environment suffix .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.
Let's write a code first and then look at what is a program file
#include<stdio.h>
int main()
{
printf("hehe\n");
return 0;
}
When we run it,
we can see our executable program in Debug, the file with the suffix .exe
Let’s take a look at our target file, we
need to go back to the previous directory to find it
So what is a data file?
We create a text file under the path of test.c, this is the data file, and the content of our chapter is about the data file
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 input and output of the data dealt with in the previous chapters all take the terminal as the object, that is, the data is input from the keyboard of the terminal, and the running results are displayed on the monitor. In fact, sometimes we will output the information to the disk, and then read the data from the disk into the memory for use when needed. What we deal with here is the file on the disk.
file name
A file must have a unique file identifier for user identification and reference.
The file name consists of 3 parts: file path + file name trunk + file suffix
例如: c:\code\test.txt
code is the path, test is the trunk of the file name, and .c is the suffix
file opening and closing
We need to open the file (fopen) when reading and writing the file, and close the file fclose when the use is over, which is similar to our dynamic memory development
In the buffer file system, the key concept is "file type pointer", referred to as "file pointer". When
we open a file, a structure will appear. The structure contains file information. We use a FILE type pointer to receive it
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf
This is the structure we use to store file information
The content contained in the FILE type of different C compilers is not exactly the same, but the same.
Whenever a file is opened, the system will automatically create a variable of the FILE structure according to the situation of the file, and fill in the information, and the user does not need to care about the details.
Generally, the variables of this FILE structure are maintained through a FILE pointer, which is more convenient to use.
Below we can create a FILE* pointer variable:
FILE* pf;//file pointer variable
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.
fopen and fclose functions
header file <stdlib.h>
Give>fopen is to open the file, fclose is to close the file, the two should be connected
When writing a program, when opening a file, a FILE* pointer variable will be returned to point to the file, which is equivalent to establishing the relationship between the pointer and the file.
//打开文件
FILE * fopen ( const char * filename, const char * mode );
//关闭文件
int fclose ( FILE * stream)
Then let's start to understand the following code, which is a simple file opening and closing
/* fopen fclose example */
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
//以读的方式打开文件
if (pf == NULL)
{
perror("fopen");
return 1;
}
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
This is how we open the test.txt file for writing
We create the file test.txt in this path
You may have some questions about these two.
One is to read the content from the file, and the other is to write the content into the file.
Let’s take a look at the output first, how to write the content into the file and read and
write in the order of the file pair
fputc
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
//以读的方式打开文件
if (pf == NULL)
{
perror("fopen");
return 1;
}
//写文件
fputc('a', pf);
fputc('b', pf);
fputc('c', pf);
fputc('d', pf);
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
After our operation, it is also successful to put abcd into our test.txt file one by one
Also note that if you write in the "w" style, the contents of the file will be destroyed first
If we comment out the content of fputc to see the result
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
//以读的方式打开文件
if (pf == NULL)
{
perror("fopen");
return 1;
}
//写文件
/*fputc('a', pf);
fputc('b', pf);
fputc('c', pf);
fputc('d', pf);*/
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
Seeing that the content of our file is gone
It can be seen from fpen that the order in which we put characters is also in order
fgetc
int fgetc(FILE* stream)
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
//以读的方式打开文件
if (pf == NULL)
{
perror("fopen");
return 1;
}
//读文件
int ch = fgetc(pf);
printf("%c", ch);
ch = fgetc(pf);
printf("%c", ch);
ch = fgetc(pf);
printf("%c", ch);
fclose(pf);
pf = NULL;
return 0;
}
When we read to the end, it will return an EOF or a null pointer
Text line output function fputs
int fputs( const char *string, FILE *stream );
Its function is the same as fputc, the effect is the output of the whole
line Let's look at the code
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
//以写的方式打开文件
if (pf == NULL)
{
perror("fopen");
return 1;
}
//写一行到文件
fputs("abcdef\n", pf);
fputs("xxxxxx\n", pf);
fclose(pf);
pf = NULL;
return 0;
}
If you want to write in one line, you don’t need to add \n.
The text line input function fgets
char* fgets(char*string,int n,FILE* steam)
Read a line from the specified stream, store it in a string, return the address of the string, and stop reading when the last character is read or \n is encountered
#include<stdio.h>
int main()
{
char arr[20];
FILE* pf = fopen("test.txt", "r");
//以读的方式打开文件
if (pf == NULL)
{
perror("fopen");
return 1;
}
//读一行到文件
fgets(arr, 6, pf);
printf("%s", arr);
fclose(pf);
pf = NULL;
return 0;
}
Here you may have questions, that is, it is clearly written 6, but why we read 5 characters, because this is a protection mechanism, sometimes we do not need to read the end of \0, so the characters we read is n-1 characters
Formatted output function fprintf
int fprintf(FILE*stream,const char* format)
fprintf is used to write formatted data to a file and send it to the formatted output stream.
Formatted data can be a structure
#include<stdio.h>
struct stu
{
char name[20];
int age;
float score;
};
int main()
{
struct stu s1 = {
"zhangsan",18,99.9f };
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fprintf(pf, "%s %d %f", s1.name, s1.age, s1.score);
fclose(pf);
pf = NULL;
return 0;
}
fscanf
int fscanf(FILE* stream,const char*format,...)
fscanf is used to read formatted data, read formatted input from stream, applicable to all input streams
#include<stdio.h>
struct stu
{
char name[20];
int age;
float score;
};
int main()
{
struct stu s1 = {
"zhangsan",18,99.9f };
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fscanf(pf, "%s %d %f", s1.name, &s1.age, &s1.score);
printf( "%s %d %f", s1.name, s1.age, s1.score);
fclose(pf);
pf = NULL;
return 0;
}
Binary output function fwrite
Write a data to the stream, and write the data pointed to by the buffer to the stream
#include<stdio.h>
struct stu
{
char name[20];
int age;
float score;
};
int main()
{
struct stu s1 = {
"zhangsan",18,99.9f };
FILE* pf = fopen("test.txt", "w+");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fwrite(&s1, sizeof(struct stu), 1, pf);
fclose(pf);
pf = NULL;
return 0;
}
The content above is binary, so I don’t quite understand it.
Then we can re-read the content in binary mode
fread
#include<stdio.h>
struct stu
{
char name[20];
int age;
float score;
};
int main()
{
struct stu s1 = {
"zhangsan",18,99.9f };
FILE* pf = fopen("test.txt", "r+");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fread(&s1, sizeof(struct stu), 1, pf);
printf("%s %d %f", s1.name, s1.age, s1.score);
fclose(pf);
pf = NULL;
return 0;
}
The above is part of the file operation, we will write it in two chapters
----------------------------------
That's all for today's sharing, thank you all