File Handling in C (fopen, fscanf, fprintf)

⚙️ C Language 🟢 Lesson 17 of 20 📅 2026 Edition
So far, everything your programs produce disappears the moment they finish running. File handling lets your C programs save data permanently and read it back later — essential for anything from config files to saved game progress.
1Opening and Closing a File
C Language ▶ Run Code
#include <stdio.h>

FILE *file = fopen("data.txt", "w");

if (file == NULL) {
    printf("Could not open file\n");
    return 1;
}

// ...work with the file...

fclose(file);

fopen() returns a FILE * pointer used for all further operations on that file, or NULL if the file couldn't be opened — always check for this before proceeding.

2Writing to a File
C Language ▶ Run Code
FILE *file = fopen("data.txt", "w");
fprintf(file, "Score: %d\n", 95);
fputs("Second line of text\n", file);
fclose(file);

fprintf() works exactly like printf(), but writes to a file instead of the screen. fputs() writes a plain string without any formatting.

3Reading from a File
C Language ▶ Run Code
FILE *file = fopen("data.txt", "r");
char line[100];

while (fgets(line, sizeof(line), file) != NULL) {
    printf("%s", line);
}

fclose(file);

fgets() reads one line at a time into your buffer, returning NULL once it reaches the end of the file — which is exactly what the while loop condition checks for.

4File Modes
⚠️ Common Mistake: Forgetting fclose() or Not Checking for NULL

Two very common file-handling mistakes: forgetting to call fclose(), which can leave data only partially written to disk and eventually exhausts your program's available file handles; and skipping the NULL check after fopen(), which causes a crash the instant you try to write to or read from a file that was never actually opened successfully.

💻 Try It Yourself

Write a program that saves three lines of text to a file, then opens the same file again and prints its contents back to the screen.

C Language ▶ Run Code
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Could not open file\n");
        return 1;
    }

    fprintf(file, "Learning C is fun\n");
    fprintf(file, "File handling makes sense now\n");
    fclose(file);

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

    return 0;
}
Run This in Our Compiler →