You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用fread()和fwrite()时检测文件读写错误?

C语言中fread()/fwrite()结合ferror()、feof()的错误检查方法

核心逻辑

fread() 和 fwrite() 的返回值是第一判断依据:它们返回成功读写的元素个数(对应函数参数里的 nmemb 参数,不是字节数)。只有当返回值小于你请求的元素个数时,才需要用 ferror() 和 feof() 区分具体原因。

具体用法

  • ferror(FILE *stream):返回非0值表示文件流发生了读写错误(比如磁盘空间不足、权限不够、硬件故障等)。
  • feof(FILE *stream):返回非0值表示已经到达文件末尾(仅对 fread() 有实际意义,fwrite() 几乎不会因为到尾返回不足)。

避坑提示

不要在调用 fread()/fwrite() 前先调用 feof() —— 这个函数只有在**已经执行过一次失败的读取操作(因到尾)**后才会置位,提前调用会导致误判。另外,ferror() 和 feof() 的状态会一直保留,直到调用 clearerr(stream) 清除或关闭文件。

代码示例

fread() 错误检查示例

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp = fopen("data.bin", "rb");
    if (!fp) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }

    int buffer[10];
    size_t req_count = 10;
    size_t actual_read = fread(buffer, sizeof(int), req_count, fp);

    if (actual_read != req_count) {
        // 读取数量不足,排查原因
        if (ferror(fp)) {
            perror("Error occurred while reading");
            fclose(fp);
            return EXIT_FAILURE;
        }
        if (feof(fp)) {
            printf("End of file reached. Read %zu elements out of %zu requested.\n", actual_read, req_count);
        }
    } else {
        printf("Successfully read all %zu elements.\n", req_count);
    }

    fclose(fp);
    return EXIT_SUCCESS;
}

fwrite() 错误检查示例

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp = fopen("output.bin", "wb");
    if (!fp) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }

    int data[] = {1,2,3,4,5,6,7,8,9,10};
    size_t req_count = 10;
    size_t actual_written = fwrite(data, sizeof(int), req_count, fp);

    if (actual_written != req_count) {
        // fwrite返回不足基本都是错误(比如磁盘满)
        perror("Error occurred while writing");
        if (ferror(fp)) {
            fprintf(stderr, "Write error confirmed.\n");
        }
        fclose(fp);
        return EXIT_FAILURE;
    } else {
        printf("Successfully wrote all %zu elements.\n", req_count);
    }

    fclose(fp);
    return EXIT_SUCCESS;
}

内容的提问来源于stack exchange,提问作者programme3219873

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:33:17