8.1 Opening and Closing Files
Files let a program save data after the program exits and read it back later. C represents an open file with FILE *.
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
fprintf(stderr, "open failed\n");
return 1;
}
fclose(fp);fopen() returns a FILE * when the file is opened successfully. If the path is wrong, the file does not exist, or the program has no permission, it returns NULL. Always check before using the file pointer.
The second argument of fopen() is the mode string. The mode decides whether the file must already exist, whether old content is kept, and where writing starts.
| Mode | Can read? | Can write? | If file does not exist | If file already exists | Write position |
|---|---|---|---|---|---|
"r" | Yes | No | Fails | Keeps content | Not writable |
"w" | No | Yes | Creates it | Clears old content | Beginning |
"a" | No | Yes | Creates it | Keeps old content | End |
"r+" | Yes | Yes | Fails | Keeps content | Beginning |
"w+" | Yes | Yes | Creates it | Clears old content | Beginning |
"a+" | Yes | Yes, append only | Creates it | Keeps old content | End for every write |
The + modes allow both reading and writing. They are useful, but be deliberate: "w+" still clears the file first, and "a+" still sends every write to the end.
Close files with fclose() when you are done. C often buffers file output in memory first; closing the file flushes that data and releases the file resource.