ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C Programming Tutorial• 7 min read

File I/O: fopen, fread, fwrite & fclose

FILE streams, text vs binary modes, error checking, and EOF

C handles file I/O through FILE* streams provided by <stdio.h>, supporting both human-readable text files and raw binary serialization.

File Stream Operations

fopen("path", "mode"): Opens a stream. Modes: "r" (read), "w" (write/truncate), "a" (append), "rb"/"wb" (binary).

Check for NULL: If a file doesn't exist or permission is denied, fopen returns NULL.

fclose(filePtr): Flushes buffers and closes the OS file descriptor.

fprintf() and fscanf(): Formatted text file I/O.

fwrite() and fread(): Fast block-level binary reads and writes directly between structs and disk.

Writing and Reading Text Files in C
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("output.txt", "w");
    if (fp == NULL) {
        perror("Failed to open file");
        return 1;
    }

    fprintf(fp, "Codexia C Mastery\nVersion: %d\n", 1);
    fclose(fp); // Flush and close file

    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What does `fopen()` return if the requested file cannot be opened due to missing permissions or a bad path?