Interview Q&A · C · 12 questions in this topic
File I/O, Errors & CLI — C Interview Q&A
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
#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
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
#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.
How do you report errors: return codes vs errno vs callbacks?
Answer
Return codes (0/-1, NULL, EOF) are the primary channel — immediate, testable, no global state. errno supplements with the reason where the call family defines it. Callbacks/log hooks serve libraries that must not print directly. stderr plus EXIT_FAILURE ends user-facing tools.
Libraries return errors; programs print them. Mixing the layers (library calling exit) ruins reusability.
Key points
- 1Return value — the primary error channel.
- 2errno — the reason, where defined.
- 3stderr/exit — only at the program edge, never in libraries.
Example
/* library: */ int sensor_read(int *out); /* 0 ok, -errno on failure */ /* program edge: */ /* if (sensor_read(&v) != 0) { fprintf(stderr, "sensor: %s\n", strerror(-rc)); } */
How do you parse command-line options (`getopt`)?
Answer
getopt (POSIX, <unistd.h>) parses short options (-v, -o file) with a spec string ("vo:" — colon means takes an argument), setting optarg/optind as it goes; getopt_long adds --long forms. Always validate missing-argument (?) and unknown-option cases, then treat remaining argv[optind..] as positional operands.
getopt beats hand-rolled parsing on clustered flags (-abc), --terminator handling, and error messages users already know.
Example
#include <unistd.h> int verbose = 0; int opt; while ((opt = getopt(argc, argv, "vo:")) != -1) { if (opt == 'v') verbose = 1; /* else if (opt == 'o') outfile = optarg; */ } /* positional args start at argv[optind] */
Text vs binary mode, buffering, and `fflush` — what must you know?
Answer
Text mode may translate newlines (Windows \n <-> \r\n); binary mode transfers bytes exactly. stdio buffers by default (line-buffered on terminals, fully-buffered on files) — fflush forces buffered output out, vital before reading paired input or across crashes. setvbuf tunes buffering (including _IONBF for unbuffered debug streams).
Mixing reads/writes on one stream ("r+") requires an intervening flush or positioning call.
Example
/* setvbuf(stdout, NULL, _IONBF, 0); // unbuffered debug output */ /* fflush(stdout); // before prompting + reading stdin */
How do `fseek`, `ftell`, `rewind` and `fgetpos` work? What are the limits?
Answer
fseek repositions (SEEK_SET/CUR/END), ftell reports the offset, rewind resets to start clearing error flags. Limits: not meaningful on pipes/sockets (non-seekable — check with errno ESPIPE), and ftell uses long (use fseeko/ftello with off_t, or _FILE_OFFSET_BITS=64, for large files).
Always check return values: seeking on a pipe fails, and large-file offsets overflow long on 32-bit builds.
Example
/* if (fseek(f, 0, SEEK_END) == 0) { long size = ftell(f); } */ /* rewind(f); // back to start, errors cleared */
How do you handle partial reads/writes and EINTR?
Answer
read/write may transfer fewer bytes than asked (signals, pipes, sockets) — loop until complete or terminal error. EINTR means a signal interrupted the call: retry the operation (or use SA_RESTART / TEMP_FAILURE_RETRY where appropriate). Distinguish retryable (EINTR, EAGAIN on non-blocking) from fatal errors.
Single-shot I/O assumptions are the quiet correctness bug in systems code.
Example
/* robust write loop: */ /* while (left > 0) { n = write(fd, p, left); */ /* if (n < 0 && errno == EINTR) continue; */ /* if (n <= 0) break; p += n; left -= n; } */
💡 Loop-to-complete plus EINTR-retry is the robust-I/O pattern in one line.
What are `stdin`, `stdout`, `stderr` and how do tools compose with them?
Answer
The three standard streams: stdin (input), stdout (normal output, bufferable/pipable), stderr (diagnostics, unbuffered so errors survive crashes). Unix tools compose by reading stdin and writing stdout, leaving humans to read stderr — pipelines (a | b) and redirection (>, 2>) depend on this split.
Respect it: data to stdout, diagnostics to stderr, exit codes for automation.
Example
/* fprintf(stderr, "error: %s\n", msg); // diagnostics channel */ /* return EXIT_FAILURE; // automation channel */
💡 Data out, diagnostics err, status code — the Unix contract in six words.
How do you write a well-behaved CLI tool (exit codes, usage, --help)?
Answer
Return 0/EXIT_SUCCESS on success, EXIT_FAILURE (or distinct codes per failure class) otherwise. Validate arguments up front with a usage message on stderr naming argv[0]. Support --help/-h and --version, read files or stdin uniformly ("-" means stdin by convention), and keep output machine-stable (no chatter on stdout).
Tools are APIs for scripts: stable output plus honest exit codes is the whole contract.
Key points
- 1Exit codes — script-readable success/failure.
- 2Usage on stderr — invoked with argv[0], on misuse.
- 3stdin/stdout discipline — composable pipelines.
What is the difference between `fclose`, `close`, and `shutdown` on sockets?
Answer
fclose flushes stdio buffers and closes the FILE* (use for fopen streams — skipping it loses buffered output). close releases a file descriptor (use for open/socket fds). shutdown(fd, HOW) partially closes a socket direction (stop sending, stop receiving, or both) while keeping the descriptor valid.
Pair correctly: fclose for FILE*, close for fds, shutdown-then-close for graceful socket teardown.
Example
/* FILE *f = fopen(...); fclose(f); // flushes + closes */ /* int fd = open(...); close(fd); // descriptor */
How do you do atomic file updates (crash-safe writes)?
Answer
Write to a temp file in the same directory, fsync it, then rename over the target — rename is atomic, so readers see old or new, never half-written. fsync the directory too for durability ordering. Direct overwrite risks torn files on crash; backup-then-replace windows still expose gaps.
Databases and editors use write-ahead/rename discipline for exactly this guarantee.
Key points
- 1Temp + fsync — durable complete content.
- 2Rename — atomic switch-over.
- 3Dir fsync — ordering that survives power loss.
💡 Temp, fsync, rename is the crash-safe recipe in three words.
Recommended resourcesAffiliate links · may earn us a commission