Seeking within a file in C
fseek moves the cursor, ftell reports it, rewind sends it home.
#include <stdio.h>
int read_tail(const char *path, char *out, size_t n) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return 0;
}
if (fseek(f, -(long) n, SEEK_END) != 0) {
rewind(f);
}
size_t read = fread(out, 1, n, f);
out[read] = '\0';
long where = ftell(f);
fclose(f);
return where > 0;
}
How it works
SEEK_SET,SEEK_CURandSEEK_ENDare the origins.- A negative offset from
SEEK_ENDreads the tail. - Text-mode seeking is only defined for values ftell returned.
Keywords and builtins used here
FILENULLcharconstifintlongread_tailreturnsize_t
The run, in numbers
- Lines
- 16
- Characters to type
- 294
- Tokens
- 111
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 67 seconds.
Step 1 of 3 in Positioning & streams, step 9 of 12 in Files & I/O.