2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
🌟🌟Author's homepage:ephemerals__
🌟🌟Column:C
3. Text files and binary files
4. Functions that control file opening and closing
2. Sequential reading and writing of files
3. Random reading and writing of files
4. Determination of the end of file reading
When we write programs, we often store data in variables. If the program exits and the memory is recycled, the data will be lost. So is there a way to save this data persistently so that the data still exists when the program is opened again? The answer is yes. And the way to do this is:File Operations。
The data of the program needs to be output to external devices and also needs to be input from external devices. For different devices, the input and output methods are different. In order to facilitate our operations on various input and output devices, there is a highly abstract concept of "stream". In C language, input and output operations on files, screens, keyboards, etc. are all performed through "streams". In general, if we want to write or read data, we need to open a stream.
When a C language program is started, by default there isThree streamsAlready opened for us:
stdin--Standard input stream, in most cases input from the keyboard.
stdout--Standard output stream, in most cases output to the display.
stderr--Standard error stream, which is output to the display in most cases.
Because these three streams are opened by default, we can directly perform input and output operations using functions such as scanf and printf.
These three streams also have types, and their types are:File pointer (FILE*)When we perform file operations, we useThe file pointer variable can indirectly find the file associated with it.。
Depending on how the data is organized, the data files are calledText filesorbinary file. Data is stored in memory in binary form.If the output is not converted to an external file, it isbinary file。
If you want to store it in ASCII code on external memory, you need to convert it before storing.A file stored in ASCII characters isText files。
How is data stored in a file?
Characters are all stored in ASCII format, and numeric data can be stored in either ASCII or binary format. For example, if the integer 10000 is output to disk in ASCII code, it will take up 5 bytes on the disk (one byte for each character), but if it is output in binary format, it will only take up 4 bytes on the disk.
After understanding these prerequisites, let's get down to business - opening and closing files. The C language provides two functions, which are responsible for opening and closing files respectively. The prototypes are as follows:
open a file:FILE * fopen ( const char * filename, const char * mode );
Close the file:int fclose ( FILE * stream );
The fopen function has two parameters:The first parameter is a string.file nameThe second parameter is the fileOpen, represented by a string. When using this function, we need to create aFile pointer variableTo receive, when the file fails to open, it will return a null pointer. Regarding the opening methods, they are listed here one by one:
Open | meaning | If the specified file does not exist |
"r" (read-only) |
To enter data, open an existing text file
| Returns a null pointer |
"w" (write only) |
To export data, open a text file
| Create a new file |
"a" (append) | Add data to the end of a text file | Create a new file |
"rb" (read-only) | To enter data, open a binary file | Returns a null pointer |
"wb" (write only) | To export data, open a binary file | Create a new file |
"ab" (append) | Add data to the end of a binary file | Create a new file |
"r+" (read-write) | Open a text file for reading and writing | Returns a null pointer |
"w+" (read and write) | Create a new text file for reading and writing | Create a new file |
"a+" (read and write) | Open a file and read and write at the end of the file | Create a new file |
"rb+" (read-write) | Open a binary file for reading and writing | Returns a null pointer |
"wb+" (read-write)
| Create a new binary file for reading and writing | Create a new file |
"ab+" (read and write)
| Open a binary file to read and write at the end of the file | Create a new file |
For the fclose function, its parameter is the file pointer, which is used to close the file pointed to by this file pointer.
Next, we try to open and close a file:
- #include <stdio.h>
-
- int main()
- {
- FILE* pf = fopen("test.txt", "w");
- if (pf == NULL)//文件打开失败则退出程序
- {
- perror("fopen");
- return 0;
- }
- printf("文件打开成功n");
- fclose(pf);
- pf = NULL;//避免出现野指针,及时制空
- return 0;
- }
It can be seen that since the opening method is "w", a file named "test.txt" does appear in the path.
Next, we introduce several functions forRead or write data in a file。
Function name | Function | Applicable to |
fgetc | Character input function | All input streams |
fputc | Character output function | All output streams |
fgets | Text line input function | All input streams |
fputs | Text line output function | All output streams |
fscanf | Formatting input functions | All input streams |
fprintf | Formatted output function | All output streams |
fread | Binary input | File input stream |
fwrite | Binary output | File output stream |
Next, let’s tryfscanfandfprintffunction:
The first parameter of these two functions is a file pointer, which is used to read and write file data. The subsequent parameters are the same as those of scanf and printf functions.
- #include <stdio.h>
-
- int main()
- {
- FILE* pf = fopen("test.txt", "w");//要写入数据,以写的形式打开文件
- if (pf == NULL)
- {
- perror("fopen");
- return 0;
- }
- fprintf(pf, "123456");//向文件中写入数据
- fclose(pf);
- pf = NULL;
- return 0;
- }
As you can see, the data has been written to the file. Next, we use the fscanf function to print the file data to the screen:
- #include <stdio.h>
-
- int main()
- {
- char str[20] = { 0 };
- FILE* pf = fopen("test.txt", "r");//要读取数据,以读的形式打开文件
- if (pf == NULL)
- {
- perror("fopen");
- return 0;
- }
- fscanf(pf, "%s", str);//读取数据到str当中
- printf(str);
- fclose(pf);
- pf = NULL;
- return 0;
- }
The function of fseek isAccording to the position and offset of the file pointerpositionFile pointer. Its prototype is as follows:
int fseek ( FILE * stream, long int offset, int origin );
Its first argument is the file pointer, the second is the offset relative to the set position, and the third is the set position.
The C language defines threeMacro, you can choose one of them as the third parameter:
SEEK_SET: The starting position of the file
SEEK_CUR: The current position of the file pointer
SEEK_END: The end of the file
After locating the file pointer, we can read or write at the specified position of the file.
The ftell function returnsThe offset of the file pointer relative to the starting position. Function prototype:
long int ftell ( FILE * stream );
The rewind function is usedReturn the file pointer to the beginning of the file. Its function prototype is:
void rewind ( FILE * stream );
1. ForText files, we can first usefgetcThe function loops through the characters in the file until EOF is reached.End of file reading。
2. Forbinary file,We usefreadThe function determines its return value:Is it less than the actual number to be read?If it is less than, thenReading ends.
For both cases, the fileAt the end of reading, we can continue to judgeReason for the end of file reading. Introduce two functions:feofandferror。
feofFunctions forDetermine the end of file readingreasonwhether or notEncountered end of file. Its prototype is as follows:
int feof ( FILE * stream );
If the file is due toRead to the end of the fileIf the reading is finished, EOF is returned; otherwise, 0 is returned.
ferrorFunctions forDetermine the end of file readingreasonwhether or notAn I/O error occurredThe prototype is as follows:
int ferror ( FILE * stream );
If the file is due toAn I/O error occurredIf the reading is completed, a non-zero value is returned; otherwise, 0 is returned.
Next, we try to write a piece of code to judge the end of file reading:
- #include <stdio.h>
-
- int main()
- {
- int c = 0;
- FILE* fp = fopen("test.txt", "r");
- if (fp == NULL)
- {
- perror("fopen");
- return 0;
- }
- while ((c = fgetc(fp)) != EOF)//返回EOF则读取结束
- {
- putchar(c);
- }
- //判断读取结束的原因
- if (ferror(fp))
- puts("I/O错误n");
- else if (feof(fp))
- puts("文件读取结束n");
- fclose(fp);
- fp = NULL;
- return 0;
- }
Today we learned about file operations, how to open and close files, how to write or read data from files, functions to adjust file pointers, and how to determine when to end file reading. If you think the blogger's talk is good, please leave a small like before leaving. Thank you for your support❤❤❤