First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

File handling

C file handling: files, streams, modes, standard I/O library functions (fopen, fclose, fgetc/fputc, fgets/fputs, fscanf/printf, fread/fwrite, fseek/ftell/rewind, feof/ferror), text vs binary, buffering, error handling, and example programs.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers often need to save results, logs, sensor readings, or configuration so they can use them later. File handling in C lets your program read data from a file and write data to a file on disk, so your output survives even after the program ends.

Key ideas

  • Stream: A stream is an abstract flow of data between your program and an input/output device or file. In C, you work with streams through the standard I/O library (stdio.h). The OS and C library may buffer streams (temporarily store data) to improve performance.
  • Text file: A text file stores human-readable characters. Lines are separated by a newline character (\n). On Windows, a text translation may map \n to CR-LF (\r\n) when reading/writing in text mode; in C text mode you use \n in the code.
  • Binary file: A binary file stores raw bytes exactly as in memory, without character translation. Suitable for storing structures and non-text data.
  • FILE object: FILE is a C library structure that represents an open stream (file or device). You work with a FILE* (pointer to FILE) returned by fopen and passed to other I/O functions.
  • File pointer (position indicator): Each open stream has a current position. For binary streams this is a byte offset from the start; for text streams it is not necessarily a byte count and is only reliably used via ftell/fseek in the same program. Reading or writing moves this position automatically. You can move it manually with fseek or rewind.
  • Buffering: The C library often uses a memory buffer between your program and the OS to reduce disk operations. For output, data may sit in the buffer until it is flushed (sent to OS) by fflush, fclose, or when the buffer fills. For input, the buffer may prefetch data. Typically, regular files are fully buffered, terminals are line-buffered, and stderr is often unbuffered.
  • Standard streams: stdin (standard input), stdout (standard output), stderr (standard error) are three FILE* that are opened automatically when your program starts. By default, stdin is the keyboard, stdout and stderr are the console.
  • Pathname: The location of a file. An absolute path starts from the root (e.g., /home/user/a.txt on Linux, C:\Users\name\a.txt on Windows). A relative path is interpreted from the program’s current working directory.
  • File mode: The mode string in fopen tells C how to open the file: for reading, writing, appending, and whether text or binary. Examples: "r", "w", "a", "r+", "w+", "a+" and adding "b" for binary like "rb".

Exact definitions useful for exams

  • Definition: File handling in C is the set of operations performed using the standard I/O library to open, read, write, seek, and close files via FILE streams, enabling persistent storage and retrieval of data.
  • Definition: Text mode is a file access mode where the C library may perform character translations (e.g., newline conversions), while binary mode performs no translation.
  • Law (Standard library contract): If fopen returns NULL, the open operation failed; no stream is opened and errno may be set. Assumption: stdio.h is included and the program checks the returned pointer before use.
  • Definition: fseek positioning: fseek(fp, offset, origin) sets the file position for stream fp by moving offset bytes relative to origin, where origin is SEEK_SET (start), SEEK_CUR (current), or SEEK_END (end). On success it returns 0 and clears the end-of-file indicator; on failure it returns nonzero. For text streams, only positions returned by ftell (or 0 with SEEK_SET) are portable.
  • Definition: ftell returns the current file position (in bytes from the start) as a long value for a binary stream. For a text stream, the value is only useful to pass back to fseek in the same program.
  • Definition: EOF is a special condition indicating no more input is available. Functions like fgetc return EOF (often -1) on end-of-file or error; use feof and ferror to distinguish.

What to draw (diagram request often seen in exams)

  • Draw a labeled block diagram of buffered I/O:
    • Left block: "Program" (label inside: "your code").
    • Middle block: "C stdio buffer" (arrows in both directions to Program). Label arrows: "fputc/fprintf/fwrite" going program→buffer and "fgetc/fscanf/fread" buffer→program.
    • Right block: "Disk file". Label arrow from buffer to disk: "OS write" and from disk to buffer: "OS read".
    • Draw a small ruler line on top of "Disk file" labeled "File positions (bytes)" with a pointer arrow labeled "Current position".

Common function groups (know what they do)

  • Open/close: fopen, fclose.
  • Character I/O: fgetc, fputc, ungetc.
  • Line/string I/O: fgets, fputs.
  • Formatted I/O: fprintf, fscanf.
  • Binary block I/O: fread, fwrite.
  • Positioning: fseek, ftell, rewind.
  • Status: feof, ferror, clearerr.
  • Flush: fflush.
  • Rename/remove: rename, remove.

Safety and portability notes

  • Always test if fopen returned NULL before using the FILE*.
  • Close every opened file with fclose to flush buffers and release OS resources.
  • Prefer binary mode ("b") for non-text data to avoid newline translation.
  • When mixing reading and writing on the same stream (modes like "r+", "w+", "a+"), you must call fflush (or a file positioning function) between a write and a subsequent read; and you must call a file positioning function (fseek, fsetpos, or rewind) between a read and a subsequent write unless the read hit EOF. Otherwise the behavior is undefined.
  • Paths are OS-specific; use forward slashes on Unix-like systems and either escaped backslashes or forward slashes on many C runtimes on Windows.
  • After printing a prompt without a trailing newline (e.g., "Source file: "), call fflush(stdout) to ensure the prompt appears before input is read on all platforms.

Formulas

#include <stdio.h> — include the standard I/O declarations. FILE *fp; — declare a file stream pointer. fp = fopen("path", "mode"); — open a file; returns NULL on failure. int fclose(FILE *fp); — close a file; returns 0 on success. int fputc(int ch, FILE *fp); — write a character; returns written char or EOF on error. int fgetc(FILE *fp); — read a character; returns unsigned char cast to int, or EOF. int fputs(const char *s, FILE *fp); — write a string (no automatic newline). char *fgets(char *s, int n, FILE *fp); — read at most n−1 chars, stop at newline or EOF; stores terminating '\0'. int fprintf(FILE *fp, const char *fmt, ...); — formatted output to a file. int fscanf(FILE *fp, const char *fmt, ...); — formatted input from a file. size_t fread(void *ptr, size_t size, size_t nmemb, FILE *fp); — read nmemb blocks of size bytes. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *fp); — write nmemb blocks of size bytes. int fseek(FILE *fp, long offset, int origin); — set position: origin is SEEK_SET, SEEK_CUR, SEEK_END. long ftell(FILE *fp); — get current file position; for binary streams this is a byte offset from start, for text streams the value is only reliable to pass back to fseek in the same program. void rewind(FILE *fp); — set position to start and clear error/EOF flags. int feof(FILE *fp); — nonzero if end-of-file has occurred for the stream. int ferror(FILE *fp); — nonzero if a read/write error has occurred. void clearerr(FILE *fp); — clear EOF and error indicators. int fflush(FILE *fp); — flush output buffer to the underlying file; for input streams its behavior is implementation-defined. int remove(const char *path); — delete a file. int rename(const char *old, const char *new); — rename or move a file.

Common mode strings for fopen (text vs binary)

  • "r" read text (file must exist)
  • "w" write text (truncate or create)
  • "a" append text (create if needed)
  • "r+" read/update text (file must exist)
  • "w+" read/update text (truncate or create)
  • "a+" read/append text (create if needed)
  • Add b for binary: e.g., "rb", "wb", "ab", "rb+", "wb+", "ab+".

Worked examples

Example 1: Write lines to a text file, then read back with line numbers

Program (save as write_read_text.c):

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *fp;
    char line[256];
    int count = 0;

    fp = fopen("greeting.txt", "w");
    if (!fp) {
        perror("fopen for write failed");
        return 1;
    }

    printf("Enter lines (empty line to finish):\n");
    while (1) {
        if (!fgets(line, sizeof(line), stdin)) break; // EOF from keyboard
        if (strcmp(line, "\n") == 0) break;         // empty line ends
        fputs(line, fp);                               // write as-is
        count++;
    }

    if (fclose(fp) != 0) {
        perror("fclose after write");
        return 1;
    }

    printf("Saved %d line(s) to greeting.txt\n", count);

    fp = fopen("greeting.txt", "r");
    if (!fp) {
        perror("fopen for read failed");
        return 1;
    }

    int lineno = 1;
    while (fgets(line, sizeof(line), fp)) {
        // Remove trailing newline for neat display
        size_t len = strlen(line);
        if (len > 0 && line[len - 1] == '\n') line[len - 1] = '\0';
        printf("%3d: %s\n", lineno++, line);
    }

    if (fclose(fp) != 0) {
        perror("fclose after read");
        return 1;
    }

    return 0;
}

Sample input (user types):

Hello, file handling!
C makes it portable.

Exact output:

Enter lines (empty line to finish):
Saved 2 line(s) to greeting.txt
  1: Hello, file handling!
  2: C makes it portable.

Note: The file greeting.txt will contain exactly these two lines with newlines.

Example 2: Copy a text file and count bytes, words, and lines

Program (save as copy_count.c):

#include <stdio.h>
#include <ctype.h>

int main(void) {
    char srcname[260], dstname[260];
    FILE *src, *dst;

    printf("Source file: ");
    if (!fgets(srcname, sizeof(srcname), stdin)) return 1;
    printf("Destination file: ");
    if (!fgets(dstname, sizeof(dstname), stdin)) return 1;

    // remove trailing newlines
    for (char *p = srcname; *p; ++p) { if (*p == '\n') { *p = '\0'; break; } }
    for (char *p = dstname; *p; ++p) { if (*p == '\n') { *p = '\0'; break; } }

    src = fopen(srcname, "r");
    if (!src) { perror("open source"); return 1; }
    dst = fopen(dstname, "w");
    if (!dst) { perror("open dest"); fclose(src); return 1; }

    long bytes = 0, lines = 0, words = 0;
    int c;
    int in_word = 0;

    while ((c = fgetc(src)) != EOF) {
        if (fputc(c, dst) == EOF) { perror("write dest"); break; }
        bytes++;
        if (c == '\n') lines++;
        if (isspace((unsigned char)c)) {
            in_word = 0;
        } else if (!in_word) {
            in_word = 1;
            words++;
        }
    }

    if (ferror(src)) perror("read source");

    fclose(src);
    if (fclose(dst) != 0) perror("close dest");

    printf("Copied. Bytes: %ld, Words: %ld, Lines: %ld\n", bytes, words, lines);
    return 0;
}

Sample run 1 (assume source file hello.txt contains exactly two lines: "Hello world.\n" and "This is C.\n"):

Source file: hello.txt
Destination file: copy.txt
Copied. Bytes: 24, Words: 5, Lines: 2

Explanation: "Hello world.\n" has 13 bytes, "This is C.\n" has 11 bytes; total 24 bytes; words separated by whitespace give 5; lines count newlines 2. Note: In text mode on Windows, CR-LF line endings are translated, so the "Bytes" count here reflects characters read, not necessarily the exact on-disk byte count; open files in binary mode ("rb"/"wb") to count raw bytes.

Example 3: Maintain student records in a binary file (add, list, find, update)

Program (save as students_bin.c):

#include <stdio.h>
#include <string.h>

typedef struct {
    int roll;
    char name[30];
    float cgpa;
} Student;

void add_records(const char *fname) {
    FILE *fp = fopen(fname, "ab"); // append binary
    if (!fp) { perror("open append"); return; }
    int n;
    printf("How many records to add? ");
    if (scanf("%d", &n) != 1 || n <= 0) { printf("Invalid number.\n"); fclose(fp); return; }
    for (int i = 0; i < n; i++) {
        Student s;
        printf("Roll: "); scanf("%d", &s.roll);
        printf("Name: ");
        int ch; while ((ch = getchar()) != '\n' && ch != EOF) {} // clear line
        if (!fgets(s.name, sizeof(s.name), stdin)) { printf("Input error.\n"); break; }
        size_t len = strlen(s.name); if (len > 0 && s.name[len-1] == '\n') s.name[len-1] = '\0';
        printf("CGPA: "); scanf("%f", &s.cgpa);
        if (fwrite(&s, sizeof(Student), 1, fp) != 1) { perror("write rec"); break; }
    }
    fclose(fp);
}

void list_records(const char *fname) {
    FILE *fp = fopen(fname, "rb");
    if (!fp) { perror("open read"); return; }
    Student s;
    printf("All records:\n");
    while (fread(&s, sizeof(Student), 1, fp) == 1) {
        printf("Roll=%d, Name=%s, CGPA=%.2f\n", s.roll, s.name, s.cgpa);
    }
    if (ferror(fp)) perror("read rec");
    fclose(fp);
}

long find_record_pos_by_roll(FILE *fp, int roll) {
    Student s;
    long index = 0;
    rewind(fp);
    while (fread(&s, sizeof(Student), 1, fp) == 1) {
        if (s.roll == roll) {
            return index * (long)sizeof(Student);
        }
        index++;
    }
    return -1; // not found
}

void find_record(const char *fname) {
    FILE *fp = fopen(fname, "rb");
    if (!fp) { perror("open read"); return; }
    int roll; printf("Enter roll to find: "); scanf("%d", &roll);
    long pos = find_record_pos_by_roll(fp, roll);
    if (pos < 0) {
        printf("Not found.\n");
    } else {
        Student s;
        if (fseek(fp, pos, SEEK_SET) != 0) { perror("fseek"); }
        else if (fread(&s, sizeof(Student), 1, fp) == 1) {
            printf("Found: Roll=%d, Name=%s, CGPA=%.2f\n", s.roll, s.name, s.cgpa);
        } else {
            perror("read rec");
        }
    }
    fclose(fp);
}

void update_cgpa(const char *fname) {
    FILE *fp = fopen(fname, "rb+"); // read/update binary
    if (!fp) { perror("open rb+"); return; }
    int roll; float cg;
    printf("Enter roll to update: "); scanf("%d", &roll);
    printf("New CGPA: "); scanf("%f", &cg);
    long pos = find_record_pos_by_roll(fp, roll);
    if (pos < 0) {
        printf("Not found.\n");
    } else {
        Student s;
        if (fseek(fp, pos, SEEK_SET) != 0) { perror("fseek"); }
        else if (fread(&s, sizeof(Student), 1, fp) != 1) { perror("read rec"); }
        else {
            s.cgpa = cg;
            if (fseek(fp, pos, SEEK_SET) != 0) { perror("fseek back"); }
            else if (fwrite(&s, sizeof(Student), 1, fp) != 1) { perror("write rec"); }
            else { printf("Updated.\n"); }
        }
    }
    fclose(fp);
}

int main(void) {
    const char *fname = "students.dat";
    int choice;
    while (1) {
        printf("\n1.Add 2.List 3.Find 4.Update 5.Exit\nChoice: ");
        if (scanf("%d", &choice) != 1) break;
        switch (choice) {
            case 1: add_records(fname); break;
            case 2: list_records(fname); break;
            case 3: find_record(fname); break;
            case 4: update_cgpa(fname); break;
            case 5: return 0;
            default: printf("Invalid choice.\n");
        }
    }
    return 0;
}

Sample run (user input shown; lines without prompt are program output):

1.Add 2.List 3.Find 4.Update 5.Exit
Choice: 1
How many records to add? 2
Roll: 101
Name: Asha
CGPA: 8.2
Roll: 102
Name: Bharat
CGPA: 7.5

1.Add 2.List 3.Find 4.Update 5.Exit
Choice: 2
All records:
Roll=101, Name=Asha, CGPA=8.20
Roll=102, Name=Bharat, CGPA=7.50

1.Add 2.List 3.Find 4.Update 5.Exit
Choice: 3
Enter roll to find: 102
Found: Roll=102, Name=Bharat, CGPA=7.50

1.Add 2.List 3.Find 4.Update 5.Exit
Choice: 4
Enter roll to update: 101
New CGPA: 8.8
Updated.

1.Add 2.List 3.Find 4.Update 5.Exit
Choice: 2
All records:
Roll=101, Name=Asha, CGPA=8.80
Roll=102, Name=Bharat, CGPA=7.50

1.Add 2.List 3.Find 4.Update 5.Exit
Choice: 5

Common mistakes

  • Forgetting to fclose files; buffers may not flush, and file descriptors may leak.
  • Using text mode for binary data, causing newline translation and corrupted data on some platforms.
  • Mixing fscanf/fgets on the same stream without handling leftover newlines, which causes empty reads. Clear the input buffer or use consistent I/O functions.
  • Assuming fgetc returns char; it returns int to represent all unsigned char values and EOF; always use int for the return type.
  • Using feof to control reading; proper pattern is while ((c = fgetc(fp)) != EOF) rather than while (!feof(fp)). feof becomes true only after a read fails at EOF.
  • Using "w" mode when you meant "a"; "w" truncates the file.
  • Forgetting to add the "b" in modes on Windows for binary files.
  • Incorrect fseek origin and offset; e.g., using SEEK_END with a positive offset.
  • Writing/reading structs with pointers inside; only the pointer value is written, not the data it points to.

For your exam

  • Short notes: File opening modes with a neat table/list and one-line meaning each; standard streams; error handling with perror, feof, ferror.
  • Programs: Typical tasks are copy a file; count characters/words/lines; merge two files; write/read student records (binary) and search/update; add line numbers while printing a file. A full-marks answer includes: correct headers, error checks for fopen/fclose, correct loop to process until EOF, clear printing, and comments if allowed.
  • Concepts/diagrams: Buffered I/O diagram with Program ↔ Buffer ↔ Disk, labeled arrows and current position indicator. Explain fseek, ftell, rewind with SEEK_SET/SEEK_CUR/SEEK_END and an example offset calculation.
  • Viva/interview points: Why int return for fgetc; difference between fflush and fclose; why feof is not a loop condition; when to choose binary vs text; safety when mixing read/write on the same stream.

Quick check

  1. State the difference between text mode and binary mode in C file handling.
  2. What does fseek(fp, -10, SEEK_END) do?
  3. Write the fopen mode to create a new binary file for reading and writing, truncating if it exists.

Answers: 1) Text mode may translate newlines and treats the file as a sequence of text characters; binary mode does no translation and treats the file as raw bytes. 2) Moves the file position to 10 bytes before the end of the file (if possible). 3) "wb+".

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?