Lesson 3 of 5
fseek, ftell & Random Access
`fseek(fp, offset, whence)` moves the file position indicator. `ftell(fp)` returns the current position. `rewind(fp)` = `fseek(fp, 0, SEEK_SET)`. Together they enable **random access** - jumping to a specific record, updating it in-place, or determining file size without reading the whole file.
fseek & ftell - File Size, Record Update & Jump
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { int id; char name[32]; float grade; } Record;
/* Get file size using fseek + ftell */
long file_size(FILE *fp) {
long cur = ftell(fp); /* save current position */
fseek(fp, 0, SEEK_END); /* jump to end */
long size = ftell(fp);
fseek(fp, cur, SEEK_SET); /* restore original pos */
return size;
}
/* Update a specific record by index (random access) */
int update_record(const char *path, int index, float new_grade) {
FILE *fp = fopen(path, "r+b"); /* open for read+write, binary */
if (!fp) { perror("fopen"); return -1; }
int count;
fread(&count, sizeof(int), 1, fp); /* read header */
if (index < 0 || index >= count) {
fprintf(stderr, "index %d out of range (0-%d)
", index, count-1);
fclose(fp); return -1;
}
/* Jump to the target record's grade field */
long offset = (long)sizeof(int) /* header */
+ (long)index * (long)sizeof(Record) /* records */
+ (long)offsetof(Record, grade); /* grade */
fseek(fp, offset, SEEK_SET);
fwrite(&new_grade, sizeof(float), 1, fp);
printf("Updated record[%d].grade to %.1f
", index, new_grade);
fclose(fp);
return 0;
}
int main(void) {
/* Write sample file */
Record rs[] = {{1,"Alice",88.5f},{2,"Bob",91.0f},{3,"Carol",79.3f}};
FILE *fp = fopen("db.bin","wb");
if (!fp) return 1;
int n = 3;
fwrite(&n, sizeof(int), 1, fp);
fwrite(rs, sizeof(Record), 3, fp);
printf("File size: %ld bytes
", file_size(fp));
fclose(fp);
/* Update Bob's grade */
update_record("db.bin", 1, 95.0f);
/* Verify */
fp = fopen("db.bin","rb");
fread(&n, sizeof(int), 1, fp);
Record loaded[3];
fread(loaded, sizeof(Record), n, fp);
fclose(fp);
for (int i = 0; i < n; i++)
printf("%d %-10s %.1f
", loaded[i].id, loaded[i].name, loaded[i].grade);
return 0;
}Common Mistakes
- `ftell` returns -1 on error - on binary streams that don't support positioning (e.g., stdin). Always check `ftell() != -1L` before using the result.
- `SEEK_SET` / `SEEK_CUR` / `SEEK_END` are the only valid whence values - don't use raw integers 0/1/2 in production. Use the named constants for readability.
- fseek in text mode has undefined behaviour with non-zero offsets - in text mode, `fseek(fp, n, SEEK_CUR)` for `n != 0` is undefined on platforms with translation (`\r\n`). For random access, always use binary mode.
Tip
Tip
Practice fseek ftell Random Access in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
fseek and ftell enable instant random-access seeking to fixed-offset records on disk
Practice Task
Note
Practice Task - (1) Write a working example of fseek ftell Random Access from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with fseek ftell Random Access is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- `fseek(fp, offset, whence)` moves the file position indicator.
- `ftell` returns -1 on error - on binary streams that don't support positioning (e.g., stdin). Always check `ftell() != -1L` before using the result.
- `SEEK_SET` / `SEEK_CUR` / `SEEK_END` are the only valid whence values - don't use raw integers 0/1/2 in production. Use the named constants for readability.
- fseek in text mode has undefined behaviour with non-zero offsets - in text mode, `fseek(fp, n, SEEK_CUR)` for `n != 0` is undefined on platforms with translation (`\r\n`). For random access, always use binary mode.
Finished this lesson?