← C roadmap

Topic 10 of 15 · Advanced

File Handling

fopen, fprintf, fgets, fread/fwrite and error checks.

Concept

Open files with fopen(path, mode): "r" read, "w" write (truncate), "a" append, add "b" for binary. Always check for NULL.

Text I/O: fprintf, fscanf, fgets, fputs. Binary I/O: fread and fwrite move raw bytes, e.g. whole structs.

Close with fclose to flush buffers. fseek/ftell move and report the file position.

Code (C17)

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("marks.txt", "w");
    if (!fp) { perror("open"); return 1; }
    fprintf(fp, "Asha 92\nRavi 78\n");
    fclose(fp);

    fp = fopen("marks.txt", "r");
    char name[20]; int m;
    while (fscanf(fp, "%19s %d", name, &m) == 2)
        printf("%s scored %d\n", name, m);
    fclose(fp);
    return 0;
}

Remember

  • Check fopen for NULL.
  • Loop on the return value, not feof().
  • Always fclose.

Interview questions

Why is while(!feof(fp)) wrong?

feof only becomes true after a read fails, so the loop runs one extra time with stale data. Check the read function's return value instead.

Text vs binary mode?

Text mode may translate line endings; binary mode reads/writes bytes exactly.

Practise C with the AI mentor

Lesson test

Take an 8-question test on “File Handling” — concepts, output prediction, bug spotting and interview questions.

Can't find a C topic you need for exams or placements? Request it and we'll add it.