Skip to main content

File I/O operations, errors, random access

Short answer

File I/O: open with fopen, read/write via functions like fprintf/fscanf, and close. Typical errors: fopen returns NULL if missing, permissions wrong; disk full; past EOF; handle by checking NULL, return values, feof/ferror. Random access uses fseek(fp, offset, SEEK_SET/CUR/EEND), ftell, rewind; for fixed-size records, fseek to (n-1)*sizeof(record) to reach nth record.

Explain the I/O operations on file with suitable example and also state the typical error situations during I/O operations in file. How the contents in the file can be randomly accessed?

I/O operations on files

A file is processed in the steps: declare FILE *fp;, open with fopen(), read/write, close with fclose(). The main functions are fprintf/fscanf (formatted), fgetc/fputc (character), fgets/fputs (string) and fread/fwrite (blocks).

FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { printf("Error\n"); return 1; }
fprintf(fp, "%d %s\n", 12, "Ram");
fclose(fp);
fp = fopen("data.txt", "r");
fscanf(fp, "%d %s", &roll, name);   /* read it back */
fclose(fp);

Typical error situations

  1. Opening a file for reading that does not exist (fopen returns NULL).
  2. Opening a file with a wrong mode, or without permission (e.g. read-only file or protected folder).
  3. Disk full or write-protected media while writing.
  4. Reading beyond the end of the file (EOF) without checking.
  5. Using a file that was never opened or has already been closed.
  6. Too many files open at the same time; invalid file name or path.

These are handled by testing the file pointer for NULL, testing the return values of fscanf/fread/fwrite, and using feof() and ferror().

Random access

Normally a file is read from the start in sequence. The following functions move the file position:

  • fseek(fp, offset, origin): moves to offset bytes from origin (SEEK_SET start, SEEK_CUR current, SEEK_END end).
  • ftell(fp): returns the current position.
  • rewind(fp): goes back to the start.

For records of equal size, the n-th record is reached directly by fseek(fp, (n-1)*sizeof(rec), SEEK_SET);.

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("rand.txt", "w+");
    if (fp == NULL) { printf("Cannot open\n"); return 1; }
    fputs("ABCDEFGHIJ", fp);

    fseek(fp, 3, SEEK_SET);                    /* 4th character */
    printf("At offset 3 : %c\n", fgetc(fp));
    printf("ftell       : %ld\n", ftell(fp));
    fseek(fp, -2, SEEK_END);                   /* 2nd from the end */
    printf("From the end: %c\n", fgetc(fp));
    rewind(fp);
    printf("After rewind: %c\n", fgetc(fp));
    fclose(fp);
    return 0;
}

Output:

At offset 3 : D
ftell       : 4
From the end: I
After rewind: A

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →