Random Access in Files (fseek)
Reading a file normally goes from start to end, like a cassette tape. But what if you need record number 500 right now? Reading 499 records first wastes time. Random access lets you jump straight there, like skipping to a song on a playlist.
In this lesson you will use fseek() to move the file position, ftell() to find where you are, and rewind() to go back to the start. You'll also find a file's size and update a record in place.
What You Will Learn
- What the file position indicator is.
- fseek with SEEK_SET, SEEK_CUR and SEEK_END.
- ftell to get the current position.
- rewind to go back to the start.
- How to find the size of a file.
- How to read and update the Nth record.
Random Access in Files Explained
Exam definition: Every open file has a file position indicator that marks where the next read or write happens. fseek(fp, offset, origin) moves it by offset bytes from origin; ftell(fp) returns its current value (bytes from the start); rewind(fp) moves it back to the beginning. Moving freely like this is called random access.
Memory trick: The file position is your bookmark. fseek = move the bookmark. ftell = "tell me the page number". rewind = go back to page one (like rewinding a tape).
Syntax of fseek(), ftell() and rewind()
int fseek(FILE *fp, long offset, int origin); /* 0 = success */
long ftell(FILE *fp); /* position, or -1L on error */
void rewind(FILE *fp); /* same as fseek(fp, 0, SEEK_SET) + clears errors */
| Origin | Value | Offset counted from | Example |
|---|---|---|---|
SEEK_SET | 0 | Beginning of the file | fseek(fp, 10, SEEK_SET): byte 10 |
SEEK_CUR | 1 | Current position | fseek(fp, -4, SEEK_CUR): 4 bytes back |
SEEK_END | 2 | End of the file | fseek(fp, 0, SEEK_END): the end |
File "ABCDEFGHIJ" (10 bytes)
byte: 0 1 2 3 4 5 6 7 8 9
A B C D E F G H I J
fseek(fp, 3, SEEK_SET) -> at 3, next fgetc = 'D'
fseek(fp, 2, SEEK_CUR) -> from 4 to 6, next fgetc = 'G'
fseek(fp, -1, SEEK_END) -> at 9, next fgetc = 'J'
fseek(fp, 0, SEEK_END); ftell(fp) = 10 -> file size
Example 1: Moving Around a Text File
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("letters.txt", "w+");
long size, pos;
int ch;
if (fp == NULL)
return 1;
fputs("ABCDEFGHIJ", fp);
printf("After writing, position = %ld\n", ftell(fp));
rewind(fp);
pos = ftell(fp); /* call separately: argument order */
ch = fgetc(fp); /* inside printf is not fixed */
printf("After rewind, position = %ld, char = %c\n", pos, ch);
fseek(fp, 3, SEEK_SET);
printf("SEEK_SET 3 -> char %c\n", fgetc(fp)); /* reads D, now at 4 */
fseek(fp, 2, SEEK_CUR);
printf("SEEK_CUR +2 -> char %c\n", fgetc(fp)); /* 4 + 2 = 6: G */
fseek(fp, -1, SEEK_END);
printf("SEEK_END -1 -> char %c\n", fgetc(fp)); /* last: J */
fseek(fp, 0, SEEK_END);
size = ftell(fp);
printf("File size = %ld bytes\n", size);
fclose(fp);
remove("letters.txt");
return 0;
}
Output
After writing, position = 10 After rewind, position = 0, char = A SEEK_SET 3 -> char D SEEK_CUR +2 -> char G SEEK_END -1 -> char J File size = 10 bytes
Code Explanation
- After writing 10 characters, the position is 10 (just past the last byte).
rewind(fp)goes back to 0, so the nextfgetcreads 'A'.fseek(fp, 3, SEEK_SET)jumps to byte 3 ('D'). Reading one char moves the position to 4.fseek(fp, 2, SEEK_CUR)moves from 4 to 6 ('G').fseek(fp, -1, SEEK_END)goes one byte before the end: 'J'.- File size trick: seek to the end with offset 0, then ftell.
How Random Access Works with Records
With fixed-size binary records, the position of record k is simple arithmetic:
offset of record k = k * sizeof(struct record) (k starts at 0)
number of records = file size / sizeof(struct record)
fseek(fp, k * sizeof r, SEEK_SET); fread(&r, sizeof r, 1, fp); -> read record k
fseek(fp, k * sizeof r, SEEK_SET); fwrite(&r, sizeof r, 1, fp); -> overwrite record k
Example 2: Read and Update the Nth Record
#include <stdio.h>
struct item
{
int code;
char name[16];
int stock;
};
int main(void)
{
struct item list[4] = { {11, "Pen", 120}, {12, "Pencil", 80},
{13, "Eraser", 45}, {14, "Notebook", 60} };
struct item it;
FILE *fp = fopen("stock.dat", "wb+");
long count;
int k;
if (fp == NULL)
return 1;
fwrite(list, sizeof list[0], 4, fp);
fseek(fp, 0, SEEK_END);
count = ftell(fp) / (long) sizeof it;
printf("Records in file: %ld\n", count);
k = 2; /* third record */
fseek(fp, k * (long) sizeof it, SEEK_SET);
fread(&it, sizeof it, 1, fp);
printf("Record %d: %d %s %d\n", k, it.code, it.name, it.stock);
it.stock -= 15; /* sold 15 erasers */
fseek(fp, k * (long) sizeof it, SEEK_SET); /* go back to it */
fwrite(&it, sizeof it, 1, fp); /* overwrite in place */
rewind(fp);
printf("Full stock list:\n");
while (fread(&it, sizeof it, 1, fp) == 1)
printf(" %d %-9s %d\n", it.code, it.name, it.stock);
fclose(fp);
remove("stock.dat");
return 0;
}
Output
Records in file: 4 Record 2: 13 Eraser 45 Full stock list: 11 Pen 120 12 Pencil 80 13 Eraser 30 14 Notebook 60
"wb+"lets one FILE pointer write, seek and read.- File size ÷ record size gives the record count without reading every record.
- After
fread, the position has moved past record 2, so wefseekback beforefwrite. Forgetting this would overwrite record 3 instead. - Only one record changed on disk: that's the power of random access.
Important Points to Remember
- fseek(fp, offset, origin): origin is SEEK_SET, SEEK_CUR or SEEK_END.
- fseek returns 0 on success.
- ftell returns the position in bytes from the start (a long).
- rewind = go to the start (and clear error/EOF flags).
- File size: fseek(fp, 0, SEEK_END); ftell(fp);
- Record k: fseek(fp, k * sizeof r, SEEK_SET).
- Seek between a read and a write on the same stream.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Arguments in wrong order: fseek(fp, SEEK_SET, 10) | Moves to the wrong place | fseek(fp, 10, SEEK_SET) |
| Writing right after fread without seeking | Overwrites the next record | fseek back first |
| Using record number from 1 without −1 | Reads the following record | Offset = (n − 1) × size |
Storing ftell in an int | Breaks for big files | Use long |
| Byte offsets in text files on Windows | \r\n makes offsets differ | Use binary mode, or only seek to ftell values |
fseek, ftell, rewind Practice Questions
- What are the three origin values of fseek?
- Write code to find the size of a file.
- What is the difference between
rewind(fp)andfseek(fp, 0, SEEK_SET)? - Each record is 32 bytes. Where does the 10th record (k = 9) start?
- After
fseek(fp, -3, SEEK_END)on a 20-byte file, what does ftell return?
Show answers
- SEEK_SET (start), SEEK_CUR (current position), SEEK_END (end).
fseek(fp, 0, SEEK_END); long size = ftell(fp);- Both move to the start; rewind also clears the error and EOF flags and returns nothing.
- 9 × 32 = byte 288.
- 17.
Coding Exercise
Write the digits "0123456789" to a file. Then, using only fseek and fgetc, print the characters at positions 9, 7, 5, 3 and 1 (from the end toward the start).
Show solution
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("digits.txt", "w+");
int pos;
if (fp == NULL)
return 1;
fputs("0123456789", fp);
for (pos = 9; pos >= 1; pos -= 2)
{
fseek(fp, pos, SEEK_SET);
printf("%c ", fgetc(fp));
}
printf("\n");
fclose(fp);
remove("digits.txt");
return 0;
}
9 7 5 3 1
Quick Quiz: fseek, ftell and rewind (MCQ)
-
Which constant means "from the end of the file"?
A)
SEEK_SETB)SEEK_CURC)SEEK_ENDD)EOF -
ftell returns:
A) File size always B) Current position in bytes C) Number of lines D) A FILE pointer
-
rewind(fp)moves the position to:A) The end B) The start C) The previous line D) Nowhere
-
fseek returns on success:
A) 1 B) 0 C) The new position D) EOF
-
To jump to record 4 (k = 4) of 20-byte records:
A)
fseek(fp, 4, SEEK_SET)B)fseek(fp, 80, SEEK_SET)C)fseek(fp, 20, SEEK_CUR)D)fseek(fp, 4, SEEK_END)
Show answers
- C:
SEEK_END. - B: current position.
- B: the start.
- B: 0.
- B: 4 × 20 = 80.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| fseek | fseek(fp, offset, origin), 0 = success |
|---|---|
| Origins | SEEK_SET (0), SEEK_CUR (1), SEEK_END (2) |
| ftell | Current position as long |
| rewind | Back to start, clears flags |
| File size | fseek(fp, 0, SEEK_END); ftell(fp) |
| Record k | k × sizeof(record) from SEEK_SET |
Frequently asked questions
- What is random access in files?
- Moving the file position directly to any byte with fseek, instead of reading from the start.
- How do you find the size of a file in C?
- fseek to the end with offset 0, then ftell gives the size in bytes.
- What is the difference between fseek and rewind?
- fseek moves anywhere and returns a status; rewind goes only to the start and also clears error flags.
Remember
- Position = bookmark: fseek moves it, ftell tells it, rewind resets it.
- Read, seek back, then write.
Next Topic
Next lesson: Error Handling in File Operations. You will handle file errors with feof, ferror, perror and errno.