Standard Library Usage and File I/O
This domain tests practical use of <stdio.h> plus the conversion and utility functions in <stdlib.h>: correct mode strings, correct return-value checking, and the distinction between EOF, a read error, and a valid byte.
File streams
FILE *fopen(const char *path, const char *mode)returnsNULLon failure - always check. Modes:"r","w"(truncates),"a"(appends), with+for update andbfor binary; on POSIX systems text and binary modes behave identically, on Windows they do not.fcloseflushes and releases the stream;fflushpushes buffered output.stdin,stdout, andstderrare pre-opened, andstderris unbuffered by default.fread/fwritereturn the number of complete items transferred, not the number of bytes.fgetc/getcharreturnintso thatEOF(negative, usually -1) is distinguishable from every valid byte.fgets(buf, n, fp)reads at mostn-1characters, keeps any newline, and NUL-terminates;fputsdoes not add a newline.feofbecomes true only after a read attempts to pass the end;ferrorreports an I/O error.perrorandstrerrortranslateerrnointo a message.
Conversions and utilities
atoicannot report failure;strtol(str, &end, base)setsendto the first unconverted character anderrnotoERANGEon overflow.strtodis the floating-point analogue.qsort(base, n, size, cmp)needs a comparator returning negative, zero, or positive values;bsearchrequires the same ordering.exit(status)runsatexithandlers and flushes streams;abort()does not.
Worked example
char buf[128];
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) { perror("data.txt"); return 1; }
while (fgets(buf, sizeof buf, fp) != NULL) {
fputs(buf, stdout);
}
if (ferror(fp)) perror("read");
fclose(fp);
fgets is used as the loop condition because it fails at end of file, at an error, or on a short read. Writing while (!feof(fp)) instead tests the flag before the failing read, so the final line is processed twice.
Traps
while (!feof(fp))- the classic duplicated last record.char c = getchar();truncatesEOF.scanf("%d", x)instead ofscanf("%d", &x), or ignoringscanf's return value, which counts converted items.- Opening with
"w"when"a"was meant, destroying the existing file. - Mixing
scanfandfgetson the same stream, leaving an unconsumed newline. - Forgetting
fclose, so buffered output never reaches the file.