Truy cập ngẫu nhiên file trong C dùng ba hàm:
ftell()rewind()fseek()
ftell()
Trả về vị trí hiện tại của con trỏ file.
int pos = ftell(FILE *fp);
Dùng để đếm số ký tự đã ghi vào file.
rewind()
Đưa con trỏ file về đầu file.
rewind(FILE *fp);
Sau khi gọi rewind, ftell luôn trả về 0.
fseek()
Di chuyển con trỏ file đến vị trí cụ thể.
fseek(FILE *fp, long offset, int whence);
Offset
- Số byte di chuyển (dương: tiến, âm: lùi).
Whence (vị trí gốc)
SEEK_SET (0)– Đầu file.SEEK_CUR (1)– Vị trí hiện tại.SEEK_END (2)– Cuối file.
Ví dụ
fseek(fp, 0, SEEK_END)– Cuối file.fseek(fp, 0, SEEK_SET)– Đầu file.fseek(fp, m, SEEK_SET)– Đi m byte từ đầu.fseek(fp, -m, SEEK_END)– Lùi m byte từ cuối.
Lỗi thường gặp
fseek(fp, -m, SEEK_SET)– Lùi trước đầu file (lỗi).fseek(fp, +m, SEEK_END)– Tiến sau cuối file (lỗi).