Input/Output and File Handling: printf/scanf, Character and Formatted I/O, File Open/Close/Read/Write
This domain tests moving data in and out of a program: the format specifiers, the return values that tell you what happened, and the file lifecycle from fopen to fclose.
Formatted I/O
printf converts values to text; scanf converts text to values and therefore needs addresses: scanf("%d", &n);. Common specifiers: %d for int, %u for unsigned, %f for float and double in printf (but %lf for double in scanf), %c for char, %s for string, %x for hexadecimal, %p for a pointer and %% for a literal percent sign. scanf returns the number of successful conversions, or EOF.
Character and line I/O
getchar/putchar and fgetc/fputc handle single characters; fgets(buf, n, stdin) reads at most n-1 characters and keeps the newline. gets is unsafe and has been removed from the standard.
Files
FILE *fp = fopen("marks.txt", "r");
if (fp == NULL) { perror("marks.txt"); return 1; }
Modes are "r", "w" (truncates), "a" (appends), with + for update and b for binary. Read and write with fprintf/fscanf or fread/fwrite, then call fclose(fp). fseek, ftell and rewind reposition the file; feof becomes true only after a read has actually hit end-of-file.
Worked example
int x, sum = 0;
while (scanf("%d", &x) == 1) sum += x;
The loop stops at the first non-numeric input or at end of file. Testing the return value avoids the double-counting produced by while (!feof(stdin)).
Traps
- Missing
&inscanf("%d", n). - Opening with
"w"when existing data had to be preserved. - Looping on
feofbefore attempting a read. - Not checking
fopenforNULL. %swithout a width overflowing the buffer.