In the process of learning the C language, functions help us organize code, while file operations allow us to “communicate” with the external world. Whether it is saving user data, reading configuration information, or handling large text and binary files, file operations are an indispensable skill.
The C language provides a powerful and flexible file operation mechanism through the standard library <stdio.h>, allowing us to easily implement basic functions such as opening, reading, writing, and closing files. Mastering these skills means that your programs will no longer be limited to transient execution in memory, but will be able to interact persistently with data on disk, truly achieving a complete “input-processing-output” flow.
Next, let us delve into the world of file operations in C, starting from basic concepts and gradually learning how to read and write files, laying a solid foundation for developing more practical programs.
1. In C language, file operations are accomplished through the standard library <stdio.h>, mainly using the following functions:
· fclose() : Close a file· fread(), fwrite() : Read and write files· fprintf(), fscanf() : Formatted read and write files· fseek(), ftell(), rewind() : File positioning· feof() : Check if the end of the file has been reached
1. Opening a file fopen()
fopen() is used to open a file and returns a file pointer; if it fails to open, it returns NULL. You can specify the mode of operation for the file:
FILE *fopen(const char *filename, const char *mode);
Common opening modes
· "r" : Open the file in read-only mode; the file must exist.· "w" : Open the file in write mode; if the file does not exist, a new file will be created; if it exists, the content will be cleared.· "a" : Open the file in append mode; if the file does not exist, a new file will be created.· "rb", "wb", "ab" : Open the file in binary mode (same functionality as r, w, a).
2. Closing a file fclose()
After completing file operations, fclose() should be called to close the file and release resources:
int fclose(FILE *stream);
If the file is closed successfully, it returns 0; if it fails, it returns EOF.
3. Reading from a file fread()
fread() is used to read data from a file and returns the number of bytes read:
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
· ptr : Pointer to the memory block where the read data will be stored.· size : Size of each data element (in bytes).· count : Number of elements to read.· stream : File pointer.
4. Writing to a file fwrite()
fwrite() is used to write data to a file:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
· ptr : Pointer to the memory block containing the data to be written.· size : Size of each data element (in bytes).· count : Number of elements to write.· stream : File pointer.
5. Formatted read and write files
fprintf() is used for formatted writing to a file:
int fprintf(FILE *stream, const char *format, ...);
fscanf() is used to read formatted data from a file:
int fscanf(FILE *stream, const char *format, ...);
6. File positioning functions
· fseek() : Set the position of the file pointer.· ftell() : Return the current position of the file pointer.· rewind() : Move the file pointer to the beginning of the file.
7. Check for end of file feof()
feof() is used to check if the end of the file has been reached:
int feof(FILE *stream);
Return value:· 0 : Not at the end of the file.· Non-0 : At the end of the file.
2. Example code
1. Reading file content
#include <stdio.h>int main() { FILE *file = fopen("xxx.txt","r"); // Open file if (file == NULL) { printf("Cannot open file\n"); return 1; } char buffer[100]; while (fgets(buffer, sizeof(buffer), file)) { printf("%s",buffer); } fclose(file); // Close file return 0;}
2. Writing to a file
#include <stdio.h>int main() { FILE *file = fopen("xxx.txt","w"); // Open file if (file == NULL) { printf("Cannot open file\n"); return 1; } // Write text data to file fprintf(file,"hello,world!\n"); // Close file fclose(file); return 0;}
Comrades! Through the study of this article, we have initially mastered the basic methods of file operations in C language, including the core operations of opening and closing files, text reading and writing, binary reading and writing. These functions, although basic, are the foundation of many practical programs.
File operations enable our programs to have the capability of data persistence, allowing programs to no longer be limited to runtime memory data, but to engage in long-term, stable data interaction with the outside world. This is an important step from “small programs” to “practical tools” and even “system software”.
I hope you can flexibly apply the knowledge related to file operations in your future studies and practices, read and write various formats of data, handle file requirements in real scenarios, and write more powerful and widely applicable C language programs. Keep up the good work; behind the files is your connection to the world of data!