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

Giải thích các hàm xử lý lỗi file trong ngôn ngữ C


File là tập hợp các bản ghi hoặc vị trí trên ổ cứng lưu trữ dữ liệu vĩnh viễn.

Các thao tác trên File

  • Đặt tên file
  • Mở file
  • Đọc từ file
  • Ghi vào file
  • Đóng file

Cú pháp cơ bản

Khai báo con trỏ file:

FILE *File_pointer;

Ví dụ: FILE *fptr;

Mở file:

File_pointer = fopen("File_name", "mode");

Ví dụ:

fptr = fopen("sample.txt", "r");
FILE *fp;
fp = fopen("sample.txt", "w");

Xử lý lỗi File (Error Handling)

Các lỗi thường gặp:

  • Đọc vượt quá cuối file (EOF).
  • Tràn thiết bị (Device overflow).
  • Mở file không hợp lệ.
  • Thao tác sai chế độ (ví dụ: ghi file mở chế độ đọc).

Hàm ferror()

Phát hiện lỗi khi đọc/ghi file.

Cú pháp: int ferror(FILE *fp);

Trả về 0 nếu thành công, khác 0 nếu có lỗi.

Ví dụ:

FILE *fp;
if (ferror(fp)) printf("Lỗi đã xảy ra");

Chương trình minh họa ferror():

#include <stdio.h>
int main() {
    FILE *fptr;
    fptr = fopen("sample.txt", "r");
    if (ferror(fptr) != 0)
        printf("Lỗi xảy ra\n");
    putc('T', fptr);  // Ghi vào file mở chế độ đọc -> lỗi
    if (ferror(fptr) != 0)
        printf("Lỗi xảy ra\n");
    fclose(fptr);
    return 0;
}

Kết quả:

Lỗi xảy ra
Lưu ý: Ghi file ở chế độ đọc sẽ gây lỗi.

Hàm perror()

In thông báo lỗi chi tiết kèm theo chuỗi mô tả.

Cú pháp: perror("chuỗi_mô_tả");

Ví dụ:

FILE *fp;
char str[30] = "Lỗi là";
perror(str);

Kết quả: Lỗi là: Bad file descriptor

Chương trình minh họa perror():

#include <stdio.h>
int main() {
    FILE *fp;
    char str[30] = "Lỗi là";
    int i = 20;
    fp = fopen("sample.txt", "r");
    if (fp == NULL) {
        printf("File không tồn tại\n");
    } else {
        fprintf(fp, "%d", i);  // Ghi vào file chỉ đọc
        if (ferror(fp)) {
            perror(str);
            printf("Lỗi do file chỉ mở để đọc\n");
        }
    }
    fclose(fp);
    return 0;
}

Kết quả:

Lỗi là: Bad file descriptor
Lỗi do file chỉ mở để đọc

Hàm feof()

Kiểm tra đã đọc đến cuối file (EOF) chưa.

Cú pháp: int feof(FILE *fp);

Trả về khác 0 nếu đã hết file, 0 nếu chưa.

Ví dụ:

FILE *fp;
if (feof(fp)) printf("Đã đến cuối file");

Chương trình minh họa feof():

#include <stdio.h>
int main() {
    FILE *fp;
    int i, n;
    fp = fopen("number.txt", "w");
    for (i = 0; i <= 100; i += 10) {
        putw(i, fp);
    }
    fclose(fp);
    
    fp = fopen("number.txt", "r");
    printf("Nội dung file:\n");
    for (i = 0; i <= 100; i++) {
        n = getw(fp);
        if (feof(fp)) {
            printf("\nĐã đến cuối file\n");
            break;
        } else {
            printf("%d ", n);
        }
    }
    fclose(fp);
    return 0;
}

Kết quả:

Nội dung file:
10 20 30 40 50 60 70 80 90 100
Đã đến cuối file.