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

So sánh fseek() và rewind() trong C

fseek()

Di chuyển con trỏ file đến vị trí tùy ý. Trả về 0 nếu thành công, khác 0 nếu lỗi.

Cú pháp

int fseek(FILE *stream, long offset, int whence);

Tham số:

  • stream – con trỏ file
  • offset – số byte dịch chuyển
  • whence – gốc tính offset:
Hằng sốÝ nghĩa
SEEK_SETĐầu file (offset >= 0)
SEEK_CURVị trí hiện tại (offset âm/dương)
SEEK_ENDCuối file (offset <= 0)

Ví dụ: Tính kích thước file

#include <stdio.h>

int main() {
    FILE *f = fopen("demo.txt", "r");
    if (!f) { printf("Khong mo duoc file"); return 1; }
    
    fseek(f, 0, SEEK_END);      // Nhay den cuoi file
    long size = ftell(f);       // Lay vi tri = kich thuoc
    printf("Kich thuoc file: %ld bytes", size);
    
    fclose(f);
    return 0;
}

Kết quả

Kich thuoc file: 78 bytes

rewind()

Đưa con trỏ file về đầu file (tương đương fseek(stream, 0, SEEK_SET)). Không trả về giá trị. Xóa cờ lỗi và EOF.

void rewind(FILE *stream);

Ví dụ

#include <stdio.h>

int main() {
    FILE *f = fopen("new.txt", "r");
    if (!f) { printf("Khong mo duoc file"); return 1; }
    
    rewind(f);                  // Ve dau file
    fseek(f, 0, SEEK_END);      // Nhay cuoi
    printf("Kich thuoc: %ld bytes", ftell(f));
    
    fclose(f);
    return 0;
}

Kết quả

Kich thuoc: 28 bytes

So sánh

Đặc điểmfseek()rewind()
Linh hoạtVị trí bất kỳChỉ đầu file
Trả vềint (0/thành công)void
Xóa cờ lỗi/EOFKhôngCó
Dùng khiCần nhảy vị trí tùy ýChỉ cần reset về đầu