Interview Q&A · C · 12 questions in this topic

File I/O, Errors & CLI — C Interview Q&A

All C topics

Real-world C — files, errno discipline, robust CLI parsing and the error-handling conventions. Part of File I/O, Errors & CLI · 202 questions in the C bank.

How do you open, read, write and close files in C?

Answer

fopen with a mode ("r", "w", "rb" for binary — the b matters on Windows), fread/fwrite/fgets/fputs/fprintf for transfer, fclose to flush and release. Always check the FILE* for NULL, check transfer counts, and fclose every opened stream — leaked descriptors exhaust limits in long-running processes.

Binary vs text mode changes newline translation: "rb"/"wb" for non-text data, always.

Example

Example.cc
#include <stdio.h>
int copy(const char *src, const char *dst) {
    FILE *in = fopen(src, "rb");
    if (!in) return -1;
    FILE *out = fopen(dst, "wb");
    if (!out) { fclose(in); return -1; }
    /* ... transfer ... */
    fclose(out); fclose(in);
    return 0;
}

💡 Check open, check counts, close everything — the file-hygiene trio.

How do you read a file robustly (and what goes wrong with `while (!feof(f))`)?

Answer

feof reports past-attempt status, not upcoming data — while (!feof(f)) runs the loop once extra on the failed read. Instead, loop on the read call itself: while (fgets(buf, sizeof buf, f)) or while ((n = fread(...)) > 0). Distinguish EOF from error with feof/ferror after the loop.

This is the single most-asked file-I/O interview question in C.

Example

Example.cc
char buf[256];
/* while (fgets(buf, sizeof buf, f)) { process(buf); } // correct */
/* while (!feof(f)) { fgets(...); }                 // runs once extra */
/* if (ferror(f)) { /* real error, not EOF */ } */

What is `errno` and how do you use it correctly?

Answer

errno (from <errno.h>) is the per-thread(?) error channel: library calls set it on failure (never clear it on success), strerror/perror translate it. Correct use: zero it before the call, check the return value first, and only then read errno — reading it unconditionally after success is meaningless.

Note errno is thread-local on modern platforms (a macro expanding to a thread call), which is what makes it usable in threaded code.

Example

Example.cc
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
errno = 0;
long v = strtol(s, &end, 10);
if (errno == ERANGE) { /* overflow: handle */ }

💡 Zero, call, check return, then read errno — the order is the discipline.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits