Move around a file deliberately
Use fseek, ftell, and rewind to revisit positions and access compatible fixed-size records.
After this lesson
You should be able to
- Position a binary stream relative to its beginning, current location, or end.
- Calculate a fixed-record offset without off-by-one mistakes.
The stream has a current position
fseek moves the stream position relative to SEEK_SET, SEEK_CUR, or SEEK_END and returns zero on success. ftell reports the current position or -1L on failure. rewind returns to the beginning and clears error and end-of-file indicators.
For portable arbitrary offsets, binary streams are simpler than text streams because text-mode position rules may translate line endings. Still check multiplication and conversion when calculating large offsets.
Jump to record k
When equal-size records begin at byte zero, zero-based record k starts at k × record size. If a user supplies record number 1 for the first record, convert it to zero-based before multiplying.
After seeking, perform the read and verify its count. A successful seek does not guarantee that a complete record exists at that position.
long offset = (long) k * (long) sizeof(struct Student);
if (fseek(file, offset, SEEK_SET) != 0) {
perror("fseek");
} else if (fread(&student, sizeof student, 1, file) != 1) {
fprintf(stderr, "Record not available\n");
}Try it yourself
Move to the fifth fixed-size record when the user counts records from one.
Need a hint?
The fifth record has zero-based index four.
Check the worked solution
Seek to 4 × sizeof record from SEEK_SET.
fseek(file, 4L * (long) sizeof record, SEEK_SET);Quick check
What does rewind(file) do?
Why this lesson exists
Syllabus mapping
Random access with fseek, ftell, and rewind
Maps to course outcomes CO3, CO4.