Skip to content
AgileLogics
5 min read

File I/O

Prerequisites: Enums

<stdio.h>'s FILE * functions read and write files:

FILE *file = fopen("notes.txt", "w");
if (file == NULL) {
    printf("Could not open file\n");
    return 1;
}
fprintf(file, "Hello, file!\n");
fclose(file);

file = fopen("notes.txt", "r");
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
    printf("%s", line);
}
fclose(file);

Common mistakes

  • Forgetting to check fopen's return value for NULL (the file might not exist, or permissions might block it).
  • Forgetting fclose — on a long-running program this leaks file handles the same way unfreed memory leaks memory.