Loading lessons...
Creating Files
Creating and Opening Files
C reads and writes files with the FILE type and functions from <stdio.h>.
fopen
fopen opens (or creates) a file and returns a file pointer:
#include <stdio.h>
int main() {
FILE *file = fopen("filename.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fclose(file);
return 0;
}
Modes
"w"- write (creates or overwrites)."a"- append (writes at the end)."r"- read (file must exist).
Always check fopen's result
fopen returns NULL when it fails (file missing, no permission). Always check before using the file.
Closing
fclose flushes and closes the file at the end.
TL;DR
fopen("name", "mode")opens/creates a file.- Always check for NULL.
fclosecloses when done.- Modes: "w" write, "a" append, "r" read.