C File I/O
There are types and functions in the library stdio.h that are used for file I/O. Reading from or writing to a file in C requires 3 basic steps:
- Open the file.
- Do all the reading or writing.
- Close the file.
For files you want to read or write, you need a file pointer:
FILE *fp;
FILE is some kind of structure that contains all the information necessary to control the file.
- Open File -- fopen(const char filename, const char mode)
fopen(-) will initialize an object of the type FILE. The parameter "filename" is file name and "mode" is s a string representing how you want to open the file. When success, fopen() returns a FILE * that can then be used to access the file, otherwise, it returns NULL. "mode" can have the following values.
| Mode | Description |
| r | Open an existing text file for reading |
| w | Open a text file for writing. If it does not exist, then create it. |
| a | Open a text file for writing in appending mode. If it does not exist, then create it. |
| r+ | Open a text file for both reading and writing |
| w+ | Open a text file for both reading and writing. If file exists, first truncate it to zero. If file does not exist, create it. |
| a+ | Open a text file for both reading and writing. If file does not exist, create it. The reading starts from the beginning but writing can only be appended |
Note For handling binary files, you need to use the following access modes.
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
- Close File -- fclose(FILE *fp )
When done with a file, it must be closed using the function fclose(-). This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file.
Closing a file is very important, if you forget to close an output file then whatever is still in the buffer may not be written out.
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file.
openfile.c is an example about how to use fopen and fclose.
/*openfile.c*/
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE * fp;
fp = fopen("testfile", "r");
if (fp == NULL) {
printf("Can't open file!\n");
exit(EXIT_FAILURE);
}
printf("Open file successfully!\n");
fclose(fp);
return 0;
}