Karnataka KSEAB SSLC JTS Programming in ANSI C study materials
Karnataka KSEAB SSLC JTS Programming in ANSI C study resources

Karnataka KSEAB SSLC JTS Programming in ANSI C: Input/Output and File Handling: printf/scanf, Character and Formatted I/O, File Open/Close/Read/Write

Karnataka KSEAB SSLC JTS Programming in ANSI C · Work through your exam, one topic at a time.

All guide sections

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 & in scanf("%d", n).
  • Opening with "w" when existing data had to be preserved.
  • Looping on feof before attempting a read.
  • Not checking fopen for NULL.
  • %s without a width overflowing the buffer.