C语言 使用 while(feof(file)) 来检查文件结束符的问题

C语言中,使用 while(feof(file)) 来检查文件结束符是错误的,因为 feof() 函数只有在尝试读取超出文件末尾后才会返回非零值。如果在读取操作之后检查 feof(),可能会导致逻辑错误。本文主要介绍feof()的使用,及C语言读取文件并判断文件是否结束是常见的操作。

1、feof()的使用

feof() 是 C 语言中的一个标准库函数,用于检查文件指针是否已经到达文件末尾(EOF,End Of File)。当对文件进行读取操作并且到达文件末尾时,feof() 会返回非零值,表示到达了文件结束。

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int number;
    // 使用 fscanf 读取文件
    while (fscanf(file, "%d", &number) == 1) {
        printf("Read number: %d\n", number);
    }

    // 检查是否到达文件末尾
    if (feof(file)) {
        printf("Reached the end of the file.\n");
    } else if (ferror(file)) {
        perror("Error reading file");
    }

    fclose(file);
    return 0;
}

2、C语言读取文件

C语言中,读取文件并判断文件是否结束是常见的操作。可以使用feof(),但在读取后才会更新状态,需谨慎使用。可以检查返回值,更加安全,直接依据读取结果判断是否成功。还可以通过fgets() 进行适合逐行读取,使用简单,适合处理文本文件。

1)使用 feof()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int number;
    while (fscanf(file, "%d", &number) == 1) {
        printf("Read number: %d\n", number);
    }

    if (feof(file)) {
        printf("Reached the end of the file.\n");
    }

    fclose(file);
    return 0;
}

2)检查返回值

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int number;
    while (fscanf(file, "%d", &number) == 1) {
        printf("Read number: %d\n", number);
    }

    if (ferror(file)) {
        perror("Error reading file");
    }

    fclose(file);
    return 0;
}

3)使用 fgets()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    char line[256];
    while (fgets(line, sizeof(line), file) != NULL) {
        printf("Read line: %s", line);
    }

    if (feof(file)) {
        printf("Reached the end of the file.\n");
    } else if (ferror(file)) {
        perror("Error reading file");
    }

    fclose(file);
    return 0;
}

推荐阅读
cjavapy编程之路首页