Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ฟังก์ชันจัดการข้อผิดพลาดไฟล์ในภาษา C (ferror, perror, feof)


ไฟล์ (File) คือที่เก็บข้อมูลถาวรบนฮาร์ดดิสก์ การดำเนินการกับไฟล์ใน C ประกอบด้วย: การตั้งชื่อ, เปิดไฟล์, อ่าน, เขียน, และปิดไฟล์

Syntax การเปิดไฟล์

FILE *fp;
fp = fopen("filename", "mode");

ข้อผิดพลาดที่พบบ่อยกับไฟล์

  • อ่านเกินขอบเขตไฟล์ (Read beyond EOF)
  • อุปกรณ์เต็ม (Device overflow)
  • เปิดไฟล์ที่ไม่มีอยู่จริง (Invalid file)
  • ดำเนินการผิดโหมด (Wrong mode operation)

1. ferror() - ตรวจจับข้อผิดพลาด Read/Write

Syntax

int ferror(FILE *fp);

คืนค่า 0 = สำเร็จ, ค่าไม่เป็น 0 = เกิดข้อผิดพลาด

ตัวอย่างโปรแกรม

#include <stdio.h>
int main() {
    FILE *fptr = fopen("sample.txt", "r");
    if (ferror(fptr)) printf("Error occurred\n");
    
    putc('T', fptr);  // พยายามเขียนในโหมดอ่าน -> จะเกิด error
    if (ferror(fptr)) printf("Error occurred\n");
    
    fclose(fptr);
    return 0;
}

ผลลัพธ์

error occurred
Note: try to write a file in the read mode results an error.

2. perror() - แสดงข้อความข้อผิดพลาดแบบละเอียด

Syntax

void perror(const char *str);

ตัวอย่างโปรแกรม

#include <stdio.h>
int main() {
    FILE *fp;
    char str[30] = "error is";
    
    fp = fopen("sample.txt", "r");
    if (fp == NULL) {
        printf("File does not exist\n");
    } else {
        fprintf(fp, "%d", 20);  // เขียนในโหมดอ่าน -> error
        if (ferror(fp)) {
            perror(str);
            printf("Error since file is opened for reading only\n");
        }
    }
    fclose(fp);
    return 0;
}

ผลลัพธ์

error is: Bad file descriptor
error since file is opened for reading only

3. feof() - ตรวจสอบ End of File

Syntax

int feof(FILE *fp);

คืนค่าไม่เป็น 0 = จบไฟล์แล้ว, 0 = ยังไม่จบ

ตัวอย่างโปรแกรม

#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("File content: ");
    for (i = 0; i <= 100; i++) {
        n = getw(fp);
        if (feof(fp)) {
            printf("\nReached end of file");
            break;
        } else {
            printf("%d ", n);
        }
    }
    fclose(fp);
    return 0;
}

ผลลัพธ์

File content is 10 20 30 40 50 60 70 80 90 100
Reached end of the file.