Skip to main content

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

2 min read
Share:
On this page (10sections)

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

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

#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

#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)

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

  • Always check fopen return value.
  • Always fclose open files (use paired open/close).
  • Use fgets with buffer size to prevent overflow.
  • For binary data, use "rb" / "wb" modes.

Common Mistakes

  • Forgetting fclose — resource leak.
  • Using "w" when you meant to append (data loss).
  • Reading with fscanf without checking return value.
  • Hard-coded paths — consider portability across operating systems.

Continue learning with these related tutorials and programs:

Related Tutorials

Search tutorials