Skip to main content

File Input Output Example in C

2 min read Updated May 29, 2025
Share:
On this page (9sections)

About this page

This is a hands-on example program in C Other Programs — write student records to a file, then read them back. It applies the concepts from the file-handling tutorials in one complete program.

Introduction

This program demonstrates reading from and writing to a text file using standard C file functions from <stdio.h>.

File I/O Functions Used

FunctionPurpose
fopen(path, mode)Open a file ("w", "r", "a")
fprintf(file, ...)Formatted write to file
fscanf(file, ...)Formatted read from file
fclose(file)Close file and flush buffers

Write and Read Example Program

#include <stdio.h>

int main(void) {
    FILE *fp;
    int num;
    char name[50];

    /* Write to file */
    fp = fopen("student.txt", "w");
    if (fp == NULL) {
        printf("Error opening file for writing\n");
        return 1;
    }
    fprintf(fp, "%d %s\n", 101, "Arun");
    fprintf(fp, "%d %s\n", 102, "Meera");
    fclose(fp);

    /* Read from file */
    fp = fopen("student.txt", "r");
    if (fp == NULL) {
        printf("Error opening file for reading\n");
        return 1;
    }

    printf("ID   Name\n");
    printf("---- ------\n");
    while (fscanf(fp, "%d %49s", &num, name) == 2)
        printf("%-4d %s\n", num, name);

    fclose(fp);
    return 0;
}

Sample Output

ID   Name
---- ------
101  Arun
102  Meera

A file named student.txt is created in the working directory with the same data.

File Open Modes

ModeMeaning
"r"Read (file must exist)
"w"Write (creates or overwrites)
"a"Append (creates if missing)
"r+"Read and write

Error Handling

Always check that fopen returns non-NULL before using the file pointer. Always call fclose when done.

Learn More

For a complete guide see File Handling in C Programming.

Learn the concept first, then study the code:

Related Tutorials

Search tutorials