In this tutorial, you'll learn how to perform random file access using C's file-positioning functions: fseek(), ftell(), and rewind(). Up to now, every file program in this series has read or written the file sequentially, one byte after another. Random access lets you jump to any position in the file — a specific record in a database, the header of an image, the trailer of a log — without reading everything before it. This is what makes databases, file formats like PNG and MP4, and any indexed file structure possible.
📝 Problem Statement
Write a program in C to demonstrate random file access using fseek(), ftell(), and rewind().
⚙️ How the Program Works
The program opens a binary file, reads some bytes, jumps to specific positions, reports its position at each step, and demonstrates the three functions in a single walk-through:
- Open the file in binary read mode (
"rb"). - Read the first 5 bytes with
fread(). Now the position is at byte 5. - Report the position with
ftell(fp)— it returns 5. - Jump to byte offset 10 with
fseek(fp, 10, SEEK_SET). The next read starts at byte 10. - Read 1 byte and print it. The position is now at byte 11.
- Jump to the end of the file with
fseek(fp, 0, SEEK_END), then callftell(fp)to get the file size. - Jump backwards by 5 bytes from the current position with
fseek(fp, -5, SEEK_CUR). - Reset to the beginning with
rewind(fp)— equivalent tofseek(fp, 0, SEEK_SET). - Read the first byte again to confirm we're back at the start.
🧠 Understanding the Three Functions
All three functions operate on the file position indicator — a "cursor" that tells the next read or write where to start. The three functions manipulate that cursor:
ftell(fp)— reports the current byte offset from the beginning of the file. Returnslong, or -1 on error.fseek(fp, offset, whence)— moves the cursor.offsetis a signed byte count;whenceis where the offset is measured from (see the table below).rewind(fp)— moves the cursor to byte 0 and clears the error indicator. Shorthand forfseek(fp, 0, SEEK_SET); clearerr(fp);.
The whence parameter
| Constant | Meaning | Example |
|---|---|---|
SEEK_SET |
Offset is from the start of the file | fseek(fp, 100, SEEK_SET) → go to byte 100 |
SEEK_CUR |
Offset is from the current position | fseek(fp, -5, SEEK_CUR) → go back 5 bytes |
SEEK_END |
Offset is from the end of the file | fseek(fp, -10, SEEK_END) → go to 10 bytes before the end |
💻 Complete C Program
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char buf[8];
long size, pos;
int ch;
/* Create a sample file of 26 bytes to work with */
fp = fopen("demo.bin", "wb");
if (fp == NULL) { printf("Error creating file.\n"); return 1; }
for (int i = 0; i < 26; i++)
fputc('A' + i, fp); /* A B C ... Z */
fclose(fp);
/* Now reopen for reading and demonstrate the three functions */
fp = fopen("demo.bin", "rb");
if (fp == NULL) { printf("Error opening file.\n"); return 1; }
/* 1. Read the first 5 bytes */
fread(buf, 1, 5, fp);
buf[5] = '\0';
printf("Read first 5 bytes: %s\n", buf);
printf("ftell() = %ld\n\n", ftell(fp));
/* 2. Jump to byte 10 using SEEK_SET */
fseek(fp, 10, SEEK_SET);
printf("After fseek(10, SEEK_SET): ftell() = %ld\n", ftell(fp));
ch = fgetc(fp);
printf("Read byte at offset 10: '%c'\n", ch);
printf("ftell() = %ld\n\n", ftell(fp));
/* 3. Find file size using SEEK_END */
fseek(fp, 0, SEEK_END);
size = ftell(fp);
printf("File size (fseek to SEEK_END + ftell): %ld bytes\n\n", size);
/* 4. Move backwards 5 bytes from current position using SEEK_CUR */
fseek(fp, -5, SEEK_CUR);
pos = ftell(fp);
printf("After fseek(-5, SEEK_CUR): ftell() = %ld\n", pos);
ch = fgetc(fp);
printf("Read byte at offset %ld: '%c'\n\n", pos, ch);
/* 5. rewind() — reset to the beginning */
rewind(fp);
printf("After rewind(): ftell() = %ld\n", ftell(fp));
ch = fgetc(fp);
printf("Read byte after rewind: '%c'\n", ch);
fclose(fp);
return 0;
}🖥️ Sample Output
ftell() = 5
After fseek(10, SEEK_SET): ftell() = 10
Read byte at offset 10: 'K'
ftell() = 11
File size (fseek to SEEK_END + ftell): 26 bytes
After fseek(-5, SEEK_CUR): ftell() = 21
Read byte at offset 21: 'V'
After rewind(): ftell() = 0
Read byte after rewind: 'A'
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
fputc('A' + i, fp) |
Writes the bytes 'A', 'B', 'C', ..., 'Z' — a 26-byte file for demonstration. |
fread(buf, 1, 5, fp) |
Reads 5 bytes into buf. After this call, the cursor is at byte 5 (just past the last byte read). |
ftell(fp) |
Returns the current byte offset from the start. After reading 5 bytes, it returns 5. |
fseek(fp, 10, SEEK_SET) |
Moves the cursor to byte 10. The next fgetc reads byte 10 (the 11th byte). |
fgetc(fp) |
Reads one byte and advances the cursor by 1. That's why ftell reports 11 after this. |
fseek(fp, 0, SEEK_END) |
Moves the cursor to the end of the file. Combined with ftell, this is the standard way to get a file's size. |
fseek(fp, -5, SEEK_CUR) |
Moves the cursor back 5 bytes from wherever it is now. After being at position 26 (end), it lands at 21. |
rewind(fp) |
Moves the cursor to byte 0 and clears the error indicator. Equivalent to fseek(fp, 0, SEEK_SET) plus clearerr(fp). |
fclose(fp) |
Closes the file. The demo file demo.bin remains on disk. |
fseek only guarantees correct positioning on files opened in binary mode. On text-mode files (especially on Windows), the byte offset that fseek accepts may not match what you expect, and the standard only guarantees that fseek(fp, 0, SEEK_SET) and fseek(fp, ftell_position, SEEK_SET) work. For precise random access, always use "rb"/"wb".
🎯 Common Use Cases
These three functions power almost every random-access file pattern in C:
| Task | Code |
|---|---|
| Find a file's size | fseek(fp, 0, SEEK_END); size = ftell(fp); |
| Read record N of a struct-array file | fseek(fp, N * sizeof(struct S), SEEK_SET); fread(&s, sizeof(struct S), 1, fp); |
| Rewrite a record in place | fseek(fp, N * sizeof(struct S), SEEK_SET); fwrite(&s, sizeof(struct S), 1, fp); (needs "rb+") |
| Read the last 8 bytes of a file | fseek(fp, -8, SEEK_END); fread(buf, 1, 8, fp); |
| Skip a fixed-size header | fseek(fp, HEADER_SIZE, SEEK_SET); |
| Iterate a file twice | rewind(fp) between passes |
| Append a record at the end | fseek(fp, 0, SEEK_END); fwrite(&s, sizeof(s), 1, fp); (or open in "ab") |
🐛 Common Pitfalls
- Text-mode files: On Windows, byte offsets in text mode don't match the actual file bytes because of
\r\ntranslation. Always use"rb"/"rb+"for random access. - Forgetting that reads advance the cursor:
ftellafterfreadreflects the position after the read, not before. - Reading past end-of-file:
fseekcan position pastEOF, but the next read returnsEOF. Check for that when computing sizes or reading tails. - Negative offsets without
SEEK_END:fseek(fp, -5, SEEK_SET)is undefined behavior — the offset would be negative. UseSEEK_ENDorSEEK_CURfor negative offsets. - Not handling
fseekerrors:fseekreturns 0 on success, non-zero on failure. Ignoring the return value can mask bugs (e.g., seeking past the end of a pipe, which is unseekable). - Seeking on a pipe or terminal: Pipes and stdin are not seekable —
fseekfails on them. Random access requires a regular file. - Using
fseekon files opened with"a": Writes always go to the end regardless of position. Use"rb+"or"wb+"for read-and-write with positioning.
💡 Tips & Best Practices
- Store the file size in a
long(orlong longfor files larger than 2 GB on 32-bit systems) —ftellreturnslong. - Between a write and a read on the same file, call
fflush(fp)first — the C standard requires it for streams opened with"+". - For files larger than 2 GB on POSIX systems, use
fseeko/ftellowithoff_tinstead offseek/ftell. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch format-specifier mismatches withlong. - Use
xxd demo.binon Linux to see the raw bytes and confirm your offsets are correct.