How to use the file type in the C programming language?
In C language, the FILE type is used to manipulate files. Here are some common operations with FILE types:
- open the file with the function fopen()
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("File could not be opened.\n");
return 1;
}
- reads data from a file
- Reads a line from a file stream.
- read from file
char buffer[100];
fscanf(file, "%s", buffer);
printf("Read: %s\n", buffer);
- use fprintf()
- The fputs() function
- Write data to a file.
fprintf(file, "Hello, World!\n");
- close()
fclose(file);
It is important to ensure that the opening and closing operations of the file are paired when using the FILE type to operate the file, in order to avoid file leakage or damage.