Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
preface
A small step every day, a big step to success. Hello everyone, I'm GW_gw, and I'm happy to learn daily trivia with you.Copy the code
The following content is from the network, if there is any infringement, please contact me to delete, this article is only used for learning exchange, not for any commercial purposes.
Abstract
This paper mainly describes some basic operations of C language file reading, text file reading, binary file reading.Copy the code
The operations for reading and writing files generally include:
- Open the file.
- Read the file and save.
- Close the file.
- Perform related operations on files.
- Open the file again and write. (or recreate the file to write)
For C, the functions needed to read and write files are in <stdio.h>, so there is no need to add additional function headers.
1. Open the file
fopen(filePath\fileName, mode)
Copy the code
Specific use:
FILE *fp = fopen("E:\ desktop \1.txt","r");Copy the code
Fopen contains two parameters, representing the file path (including the file name) and the access mode, mode.
Mode can be the following values:
r | rb | Opens an existing text file (binary file), allowing only read operations |
---|---|---|
w | wb | Open a text file (binary file) and write to it. If the file does not exist, it is automatically created and written to. If the file exists, the system deletes the original file and writes the file again. |
a | ab | Open the text file (binary file), append write. If the file does not exist, it is created automatically. |
r+ | rb+ / r+b | Opens an existing text file (binary file), allowing read and write operations |
w+ | wb+ / w+b | Open a text file (binary file) for read and write operations. If the file does not exist, it is automatically created and written to. If the file exists, the system deletes the original file and writes the file again. |
a+ | ab+ / a+b | Open a text file (binary file), allowing read/write operations, or append writes in the case of writes. If the file does not exist, it is created automatically. |
2. Close the file
fclose(fp);
Copy the code
This function is used to close a file and free up any memory used for the file. The function returns 0 if closed correctly, EOF otherwise.
conclusion
These are the basic operations for opening and closing text files and binaries. If there is something wrong, welcome to dig friends to criticize and correct.