当前位置:网站首页>Explanation of C language file operation function
Explanation of C language file operation function
2022-07-25 02:19:00 【JDSZGLLL】
introduction
We may want to store specific data relatively stably in the computer , And don't want the program to be destroyed at the end . This involves the problem of data persistence , Our general methods of data persistence are , Store the data in a disk file 、 Stored in the database .
Using files, we can store data directly on the hard disk of the computer , Data persistence is achieved .
Want to achieve this function , File manipulation functions must be mastered , It can conveniently and quickly process the file accordingly .
file name
A file should have a unique file ID , So that users can identify and reference .
The filename contains 3 part : File path + File name trunk + file extension .
For convenience , The file ID is often referred to as the file name .
The file pointer
First , We have to accept a concept , That is the operation of the program on the file ( That is, the operation of hardware ), Not directly , Instead, create a file type structure , Operate the members in this structure to realize the operation of files .
Each used file has a corresponding file information area in memory , It is used to store information about files ( Such as the name of the document , File status and current file location, etc ). This information is stored in a structure variable . The structure type is system declared , The name FILE.
It's usually through a FILE To maintain this FILE Structural variables , This is more convenient to use .
Opening and closing of files
The file should be opened before reading and writing , The file should be closed after use .
// Open file
FILE * fopen ( const char * filename, const char * mode );
// Close file
int fclose ( FILE * stream );| How files are used | meaning | If the specified file does not exist |
| “r”( read-only ) | To enter data , Open an existing text file | error |
| “w”( Just write ) | To output data , Open a text file | Create a new file |
| “a”( Additional ) | Add data to the end of the text file | Create a new file |
| “rb”( read-only ) | To enter data , Open a binary file | error |
| “wb”( Just write ) | To output data , Open a binary file | Create a new file |
| “ab”( Additional ) | Add data to the end of a binary file | error |
| “r+”( Reading and writing ) | For reading and writing , Open a text file | error |
| “w+”( Reading and writing ) | For reading and writing , Suggest a new file | Create a new file |
| “a+”( Reading and writing ) | Open a file , Read and write at the end of the file | Create a new file |
| “rb+”( Reading and writing ) | Open a binary file for reading and writing | error |
| “wb+”( Reading and writing ) | For reading and writing , Create a new binary file | Create a new file |
| “ab+”( Reading and writing ) | Open a binary file , Read and write at the end of the file | Create a new file |
Sequential reading and writing of files
The following functions should be used for sequential reading and writing of files :
| function | Function name | Apply to |
| Character input function | fgetc | All input streams |
| Character output function | fputc | All output streams |
| Text line input function | fgets | All input streams |
| Text line output function | fputs | All output streams |
| Format input function | fscanf | All input streams |
| Format output function | fprintf | All output streams |
| Binary input | fread | file |
| Binary output | fwrite | file |
Let's look at a piece of code :
int main()
{
// Open file
FILE* pFile = fopen("myfile.txt", "w");
// File operations
if (pFile != NULL)
{
fputs("fopen example\n", pFile);
fputs("fopen example\n", pFile);
fputs("fopen example\n", pFile);
// Close file
fclose(pFile);
}
return 0;
}FILE* pFile = fopen("myfile.txt", "w");
The first step is to open the file , Return an address to the file pointer pFile, Of course , It may open successfully or fail . If opening fails ,fopen Function will return NULL, So we have to judge
if (pFile != NULL) Only the return value is not NULL, The program will continue to operate on the file , Or it's over .
When the program successfully opens the file ,fputs("fopen example\n", pFile); Is to output a line of string to the file ,"fopen example" It's the content ,pFile Point to the corresponding file .
Finally close the file , Let's see the final result :

We can know , If you want to wrap , You need to add ‘\n’.
On the basis of the original, let's take a look fgets The use of :

The first is the way to open the file , It's read-only ("r"),fgets(arr, 4, pFile); among arr Is the pointer to the array used to store the read string ,4 Is the maximum number of characters read ( It includes '\0'), So only three characters are printed ,pFile It's a file pointer . however ,fgets At most one line can be read at a time .

Although the maximum number of read characters is set to 90, But what is read in the end is still the content before the newline character .
fprintf and fscanf
fprintf Is to output formatted data to the corresponding stream :

fscanf Is to convert the formatted data from the stream into assigned variables :

Random reading and writing of documents
fseek
int fseek ( FILE * stream, long int offset, int origin );Locate the file pointer according to its position and offset .
ftell
long int ftell ( FILE * stream );Returns the offset of the file pointer from its starting position .
rewind
void rewind ( FILE * stream ); Return the file pointer to the beginning of the file
边栏推荐
- Mobile Robotics (3) Kalman filter
- What are the basic skills of engineers? How to practice? -- Learning experience sharing "suggestions collection"
- Standard transfer function
- Jsonp solves cross domain plug-ins (JS, TS)
- MySQL advanced (13) command line export import database
- Research and application of scientific data management strategy for high energy synchrotron radiation source
- Componentization and modularization
- Application status of typical marine environmental observation data products and Its Enlightenment to China
- Grpc sets connection lifetime and server health check
- My creation anniversary (3rd Anniversary)
猜你喜欢

Detailed explanation of the principles and differences between static pages and dynamic pages

Dynamic memory development

Google launched another "man grabbing war" for core making, and Intel's 17 year veteran joined!

My creation anniversary (3rd Anniversary)

Solution to the occupation of project startup port

Data integration | what are the tools for data integration at home and abroad?

Coal industry supply chain centralized mining system: digitalization to promote the transformation and upgrading of coal industry

How can arm access the Internet through a laptop?

VRRP virtual redundancy protocol configuration

Win10 configuring CUDA and cudnn
随机推荐
Failed to create data snapshot: lock file [/siyuan/data/assets/image- 2022070216332-jijwccs.png failed: open /siyuan/data/assets/image- 2022070216332-jijwccs.png: permission denied; unable to lock fil
Ogg data extraction delay is large
Simulate the implementation of strstr
B2B e-commerce trading platform of heavy metal industry: breaking the state of data isolation and improving the benefits of heavy metal industry
Babbitt | metauniverse daily must read: Dubai launched the national metauniverse strategy, which plans to increase the number of related companies of metauniverse by five times in the next five years
Android memory optimized disk cache
Academicians said: researchers should also support their families. They can only do short-term and fast research if they are not promoted
Antdb database products were selected into the global database industry map (2022) of the China Academy of communications and communications
Rightmost × Microframe, high quality heif image coding and compression technology
Data integration | what are the tools for data integration at home and abroad?
Contemporary fairy quotations
Componentization and modularization
6-11 vulnerability exploitation - use the built environment to send emails
Arthas case: dynamic update application logger level
What do growth enterprises need most to build a data-driven organization?
BMW I3 based on clar architecture is not a simple "oil to electricity" product
Promise basic use
It's still a synchronization problem
Keepalivetime=0 description of ThreadPoolExecutor
JVM Foundation