Skip to study material
← Question index

QUESTION 14

Explain file positioning with fseek, ftell, rewind, fgetpos and fsetpos.

5 marks

Answer in brief

Positioning functions allow a stream to revisit suitable locations instead of always reading sequentially.

Main operations

  1. fseek requests a position relative to SEEK_SET, SEEK_CUR or SEEK_END, subject to stream restrictions.
  2. ftell obtains a position indication and must be checked for failure.
  3. rewind returns to the beginning and clears indicators, without a returned status.
  4. fgetpos saves a position in fpos_t; fsetpos restores a valid saved position.

Binary record example

The demonstration writes three ints, then uses a checked fseek with offset sizeof(int) from SEEK_SET. This selects the second native int record, which is read and displayed as 20. The offset is small and representable in long for this example.

Text-stream restrictions

Do not assume arbitrary byte arithmetic works on text positions. A portable text-stream seek uses permitted forms such as offset zero or a suitable earlier ftell value with SEEK_SET. For saved positions, fgetpos and fsetpos can preserve stream state represented by fpos_t.

Checking and updates

fseek returns zero on success. A successful seek clears the EOF indicator. Positioning can also provide a required transition between reading and writing on an update stream. Do not use an unchecked failed seek and then claim a particular record was accessed.

Cost

The interface does not guarantee a universal O(1) physical-device seek. Direct fixed-record indexing avoids comparing every previous record, but filesystem and device costs remain implementation-dependent. Variable-length records require a separate way to discover their boundaries.

Complete C example

This demonstration creates or replaces its codebhavya_* sample file in the working directory. Run it in a separate test directory. Native binary examples use one compatible implementation.

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>

int main(void)
{
    int a[3] = {10, 20, 30}, value;
    FILE *fp = fopen("codebhavya_position_demo.bin", "wb");
    if (fp == NULL) { puts("Open failed"); return 1; }
    if (fwrite(a, sizeof a[0], 3, fp) != 3) { fclose(fp); puts("Write failed"); return 1; }
    if (fclose(fp) != 0) { puts("Close failed"); return 1; }
    fp = fopen("codebhavya_position_demo.bin", "rb");
    if (fp == NULL) { puts("Open failed"); return 1; }
    if (fseek(fp, (long)sizeof(int), SEEK_SET) != 0 || fread(&value, sizeof value, 1, fp) != 1) {
        fclose(fp); puts("Position/read failed"); return 1;
    }
    if (fclose(fp) != 0) { puts("Close failed"); return 1; }
    printf("Second = %d\n", value);
    return 0;
}

Sample input and output

The example uses values in the code.

Output

Second = 20