Skip to main content
Browse topics

File Handling in C Programming (fopen, fprintf, fscanf, fclose)

2 min read Updated June 30, 2026
Share

About this page

This is a practical quick-start for file handling with fopen, fprintf, fscanf and fclose. Use it when you want working code fast.

For full coverage of file modes, binary files, and advanced operations, see File Management. For a complete runnable program, see File Input Output Example Program.

Introduction

C treats files as streams. The <stdio.h> library provides fopen, fprintf, fscanf, fgets, fputc and fclose for text file operations.

Opening and Closing Files

c
FILE *fp = fopen("data.txt", "w");   /* write (create/truncate) */
FILE *fp = fopen("data.txt", "r");   /* read */
FILE *fp = fopen("data.txt", "a");   /* append */

if (fp == NULL) {
    perror("fopen failed");
    return 1;
}

fclose(fp);

Write to a File

c
#include <stdio.h>

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

    fprintf(fp, "Hello, File!\n");
    fprintf(fp, "Number: %d\n", 42);

    fclose(fp);
    printf("Data written to output.txt\n");
    return 0;
}

Read from a File

c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("output.txt", "r");
    char line[256];

    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    while (fgets(line, sizeof(line), fp) != NULL)
        printf("%s", line);

    fclose(fp);
    return 0;
}

Sample Output (after running write then read)

plaintext
Hello, File!
Number: 42

File Open Modes

ModeMeaning
"r"Read — file must exist
"w"Write — creates or truncates
"a"Append — creates if missing
"r+"Read and write
"rb" / "wb"Binary read/write

Best Practices

Common Mistakes

Continue learning with these related tutorials and programs:

Frequently Asked Questions

What does this C program do?
It is a C example program that demonstrates File Handling in C Programming (fopen, fprintf, fscanf, fclose), including the complete source code and the expected sample output.
How do I compile and run this C program?
Save the code in a `.c` file, compile it with `gcc filename.c -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data, arrays and conditional logic, illustrating a common pattern in C programming.

Related tutorials

Search tutorials