Example 1 — Read the third record directly
Skip two integers without reading them.
#include <stdio.h>
int main(void) {
int vals[] = {10, 20, 30, 40, 50};
FILE *fp = fopen("seek.bin", "wb");
if (!fp) return 1;
fwrite(vals, sizeof vals[0], 5, fp);
fclose(fp);
fp = fopen("seek.bin", "rb");
if (!fp) return 1;
int x;
fseek(fp, 2 * (long)sizeof(int), SEEK_SET);
fread(&x, sizeof x, 1, fp);
printf("third value: %d\n", x);
fseek(fp, 0, SEEK_END);
printf("items in file: %ld\n", ftell(fp) / (long)sizeof(int));
fclose(fp);
return 0;
} How It Works
fseekjumps 2 ints (8 bytes) from the start.- After the read the position moves to the next item.
SEEK_ENDplusftellgives the file size in bytes; dividing bysizeof(int)gives the item count.
