MCS-201 · Unit 8

File Handling

Section 7 of 8

Block 2 · Unit 8File Handling15 min · Section 7 of 8

8.7Random Access and Positioning the File Pointer

Covers IGNOU MCS-201 §8.4, 8.5

So far every program has read files from the beginning to the end. Sometimes you need record number 500 without reading the 499 before it, or you need to change one record in place. That is random access.

Sequential versus random access

Sequential accessRandom (direct) access
How data is reachedIn order, from the beginningDirectly at any position
AnalogyA cassette tapeA music playlist where you tap any song
C functionsRead and write functions onlyPlus fseek, ftell, rewind
Best forProcessing every record (reports, copying)Searching or updating individual records
File typeText or binaryUsually binary files with fixed-size records

The file position indicator

Every open stream has a file position indicator: the byte number (counting from 0) where the next read or write will happen. Each read or write moves it forward automatically. Random access means moving it yourself.

FunctionPrototypePurpose
fseekint fseek(FILE *fp, long offset, int origin);Move the position to offset bytes from origin; returns 0 on success, non-zero on failure
ftelllong ftell(FILE *fp);Return the current position, or −1L on error
rewindvoid rewind(FILE *fp);Go back to the beginning (also clears the error indicator)

The origin argument is one of three macros:

OriginOffset counted fromExampleMeaning
SEEK_SETThe beginningfseek(fp, 10L, SEEK_SET)Go to byte 10
SEEK_CURThe current positionfseek(fp, -2L, SEEK_CUR)Go back 2 bytes
SEEK_ENDThe end of the filefseek(fp, -2L, SEEK_END)Go to 2 bytes before the end

Their values are 0, 1 and 2 on common systems, but always use the names. For text files, the standard only guarantees fseek to the beginning, to the end, or to a position previously returned by ftell, because newline translation can change byte counts; use binary mode for byte-exact positioning.

position of record n=n×sizeof(record)(n=0,1,2,…)\text{position of record } n = n \times \text{sizeof(record)} \quad (n = 0, 1, 2, \ldots)

Updating a record in place

To change one record: open the file with "r+b", read records until the right one is found, move back by one record with fseek(fp, -(long)sizeof st, SEEK_CUR), and write the modified record over the old one.

Key takeaways

  • Sequential access reads in order; random access jumps to any position.
  • fseek moves the position relative to SEEK_SET, SEEK_CUR or SEEK_END.
  • ftell gives the current position; rewind returns to the start.
  • Update a record by reading it, seeking back one record and writing it again, in a file opened with "r+b".

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

Which call moves to the beginning of the file?

Show answer

Answer: A. fseek(fp, 0L, SEEK_SET);

Offset 0 from the beginning is the start of the file; rewind(fp) does the same and also clears the error indicator.

Question 2 · multiple choice

How can a program find the size of a binary file in bytes?

Show answer

Answer: C. fseek(fp, 0L, SEEK_END); followed by ftell(fp)

After moving to the end, the position equals the number of bytes in the file. sizeof(fp) is just the size of the pointer.

Question 3 · multiple choice

A file stores records of 40 bytes each. Which call positions the stream at the start of record number 5 (counting from 0)?

Show answer

Answer: D. fseek(fp, 200L, SEEK_SET);

Record 5 begins at 5 × 40 = 200 bytes from the beginning. 160 would be record 4.

Question 4 · multiple choice

A file contains PROGRAM (7 bytes). What does this program print?

C · seek_quiz.c
#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("word.dat", "w+b");
    if (fp == NULL)
        return 1;
    fputs("PROGRAM", fp);
    fseek(fp, 1L, SEEK_SET);
    putchar(getc(fp));
    fseek(fp, 2L, SEEK_CUR);
    putchar(getc(fp));
    fseek(fp, -1L, SEEK_END);
    putchar(getc(fp));
    putchar('\n');
    fclose(fp);
    return 0;
}
Show answer

Answer: B. RRM

Byte 1 is ‘R’ (position becomes 2); moving 2 forward gives position 4, ‘R’; one byte before the end is position 6, ‘M’.

Question 5 · multiple choice

What does ftell return?

Show answer

Answer: C. The current position, measured in bytes from the beginning

For a binary stream ftell gives the byte offset from the start of the file, or −1L on error.

Question 6 · short answer

Explain why the update program opens the file with "r+b" and why it calls fseek before fwrite.

Show worked answer

"r+b" opens an existing binary file for both reading and writing without erasing it; "w+b" would destroy the records, and "a+b" would force every write to the end of the file. After fread reads the matching record, the position is already at the start of the next record, so fseek(fp, -(long)sizeof st, SEEK_CUR) moves back by one record; the following fwrite then overwrites the matching record instead of the one after it.

↑ ↓ move↵ openTab switch type