Hàm fseek() di chuyển con trỏ file đến vị trí cụ thể. Trả về 0 nếu thành công, khác 0 nếu thất bại.
Cú pháp
int fseek(FILE *stream, long int offset, int whence);
Tham số
- stream — con trỏ
FILE. - offset — số byte dịch chuyển từ vị trí
whence. - whence — vị trí tham chiếu:
| Hằng số | Ý nghĩa |
|---|---|
| SEEK_SET | Đầu file (offset ≥ 0) |
| SEEK_CUR | Vị trí hiện tại (offset có thể âm/dương) |
| SEEK_END | Cuối file (offset thường ≤ 0) |
Ví dụ: Tính kích thước file
File demo.txt:
This is demo text! This is demo text! This is demo text! This is demo text!
#include <stdio.h>
void main() {
FILE *f = fopen("demo.txt", "r");
if (!f) { printf("Khong mo duoc file"); exit(0); }
fseek(f, 0, SEEK_END);
printf("Kich thuoc file: %ld bytes", ftell(f));
getch();
}
Kết quả
Kich thuoc file: 78 bytes
Lưu ý: Với file lớn (>2GB), dùng fseeko() (offset kiểu off_t). Luôn kiểm tra giá trị trả về để phát hiện lỗi.