100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

File Handling in C

Learn C file handling with fopen, fclose, fprintf, and fscanf, including file modes, error checks, and a working example.

File Handling & PreprocessorIntermediate12 min readJul 7, 2026
Analogies

1. Introduction

File handling in C lets a program read from and write to files stored on disk, so data can persist beyond the lifetime of the running process. The standard I/O library (stdio.h) provides a FILE pointer abstraction and a set of functions — fopen(), fclose(), fprintf(), fscanf(), fgets(), fputs(), fread(), and fwrite() — that work uniformly whether the underlying stream is a text file, a binary file, or even standard input/output. Mastering file handling is essential for tasks such as logging, configuration parsing, data serialization, and building command-line utilities.

🏏

Cricket analogy: File handling is like recording a match's scorecard on paper so the result persists after the players leave the ground, with fopen/fclose acting like opening and closing the official scorebook for entries.

2. Syntax

c
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
char *fgets(char *str, int n, FILE *stream);
int fputs(const char *str, FILE *stream);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

3. Explanation

fopen() opens a file and returns a FILE* handle, or NULL if the operation fails (e.g., the file does not exist in read mode, or permissions are insufficient). The mode string controls behavior: "r" opens an existing file for reading, "w" creates a new file for writing (truncating an existing one), "a" opens for appending (writing at the end, creating the file if absent), and "r+", "w+", "a+" add read/update capability. Appending a "b" (e.g., "rb", "wb") opens the file in binary mode, which matters on platforms that translate newline characters in text mode. Once open, fprintf()/fscanf() perform formatted text I/O similar to printf()/scanf(), while fread()/fwrite() move raw bytes for binary records. fclose() flushes any buffered output and releases the FILE* handle back to the OS; every successfully opened file must eventually be closed.

🏏

Cricket analogy: fopen's "r" mode is like reviewing an existing scorecard without altering it, "w" is like starting a fresh scorecard that erases the old one, and "a" is like adding new overs to the end of today's card; a "b" suffix is like recording raw ball-by-ball sensor data instead of readable text, and fclose is like officially signing off and submitting the card.

4. Example

c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("notes.txt", "w");
    if (fp == NULL) {
        perror("fopen failed");
        return 1;
    }

    fprintf(fp, "Line 1: Hello, file!\n");
    fprintf(fp, "Line 2: %d + %d = %d\n", 2, 3, 5);
    fclose(fp);

    fp = fopen("notes.txt", "r");
    if (fp == NULL) {
        perror("fopen failed");
        return 1;
    }

    char buffer[100];
    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("%s", buffer);
    }
    fclose(fp);

    return 0;
}

5. Output

text
Line 1: Hello, file!
Line 2: 2 + 3 = 5

Always check the return value of fopen() for NULL before using the FILE pointer — writing or reading through a NULL pointer causes undefined behavior. Just as important: always call fclose() on every file you open, even along error-return paths, otherwise buffered writes may never reach disk and you leak file descriptors.

Use "a" mode instead of "w" when you want to preserve existing file content and add new data at the end — "w" mode silently truncates the file to zero length first.

6. Key Takeaways

  • fopen() returns a FILE* or NULL on failure — always check before use.
  • Mode strings ("r", "w", "a", plus "+" and "b" variants) control read/write/append and text/binary behavior.
  • fprintf/fscanf handle formatted text; fread/fwrite handle raw binary records.
  • fclose() flushes buffers and releases the handle — never skip it.
  • "w" truncates an existing file; "a" appends without truncating.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#FileHandlingInC#File#Handling#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep