Reading & Writing Files in C

File handling in C allows programs to read data from files and write data to files using the standard library. The main functions are: fopen(), fprintf(), fscanf(), fputs(), fgets(), fread(), fwrite(), fclose().

Why File Handling?

Important File Functions

File Opening Modes

Reading Files

You can read files using:

Writing Files

Error Handling

Always check fopen() result to avoid crashes.

All 10 File Read/Write Examples

#include <stdio.h>

/* Example 1 – Write text to file */
int main() {
    FILE *f = fopen("data.txt", "w");
    fprintf(f, "Hello C File Handling!");
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 2 – Append text */
int main() {
    FILE *f = fopen("data.txt", "a");
    fputs(" New line added.\n", f);
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 3 – Read entire file character by character */
int main() {
    FILE *f = fopen("data.txt", "r");
    int ch;
    while((ch = fgetc(f)) != EOF){
        putchar(ch);
    }
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 4 – Read line using fgets() */
int main() {
    FILE *f = fopen("data.txt", "r");
    char line[100];
    fgets(line, sizeof(line), f);
    printf("%s", line);
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 5 – Write multiple values using fprintf() */
int main() {
    FILE *f = fopen("marks.txt", "w");
    fprintf(f, "Math: %d\nScience: %d", 90, 85);
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 6 – Read formatted data with fscanf() */
int main() {
    FILE *f = fopen("marks.txt", "r");
    int m, s;
    fscanf(f, "Math: %d\nScience: %d", &m, &s);
    printf("%d %d", m, s);
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 7 – Write binary data */
int main() {
    int nums[3] = {1,2,3};
    FILE *f = fopen("bin.dat", "wb");
    fwrite(nums, sizeof(int), 3, f);
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 8 – Read binary data */
int main() {
    int nums[3];
    FILE *f = fopen("bin.dat", "rb");
    fread(nums, sizeof(int), 3, f);
    printf("%d %d %d", nums[0], nums[1], nums[2]);
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 9 – Count number of characters */
int main() {
    FILE *f = fopen("data.txt", "r");
    int count = 0, ch;
    while((ch = fgetc(f)) != EOF) count++;
    printf("Characters: %d", count);
    fclose(f);
    return 0;
}
#include <stdio.h>

/* Example 10 – Copy content from one file to another */
int main() {
    FILE *src = fopen("input.txt", "r");
    FILE *dst = fopen("output.txt", "w");

    int ch;
    while((ch = fgetc(src)) != EOF){
        fputc(ch, dst);
    }

    fclose(src);
    fclose(dst);
    return 0;
}