Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Hàm fseek() trong C/C++

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_CURVị trí hiện tại (offset có thể âm/dương)
SEEK_ENDCuố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.