【问题标题】:fread() Returning Zero Bytes Read: I Don't Understand Whyfread() 返回零字节读取:我不明白为什么
【发布时间】:2011-12-12 23:11:27
【问题描述】:

我浏览了手册页,并在线阅读了一些示例。我所有其他系统和标准调用似乎都在处理相同的数据,为什么不 fread?

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

unsigned char *data;

int main(int argc, char *argv[])
{
    FILE *fp = fopen("test_out.raw", "rb");
    if (fp == NULL) {
        fprintf(stderr, "ERROR: cannot open test_out.raw.\n");
        return -1;
    }

    long int size;
    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);
    if(size < 0) {
        fprintf(stderr, "ERROR: cannot calculate size of file.\n");
        return -1;
    }

    data = (unsigned char *)calloc(sizeof(unsigned char), size);
    if (data == NULL) {
        fprintf(stderr, "ERROR: cannot create data.\n");
        return -1;
    }

    if (!fread(data, sizeof(unsigned char), size, fp)) {
        fprintf(stderr, "ERROR: could not read data into buffer.\n");
        return -1;
    }

    int i;
    for (i = 0 ; i < size; ++i) {
        if (i && (i%10) == 0) putchar('\n');
        fprintf(stdout, " --%c-- ", (unsigned char)(data[i]));
    }

    free(data);
    fclose(fp);
    return 0;
}

【问题讨论】:

    标签: c file-io std fread fseek


    【解决方案1】:

    您使用fseek 移至文件末尾,然后您尝试从中读取 - 但是,由于您已经在文件末尾,读取失败,因为没有什么可读取的了。

    在尝试读取之前,使用另一个 fseek 回到文件开头:

    fseek(fp, 0L, SEEK_SET);
    

    或者,甚至更简单,使用rewind:

    rewind(fp);
    

    【讨论】:

      【解决方案2】:

      您正在调用 fseek 来查找文件末尾,这会将位置指示器移动到文件末尾,因此当您调用 fread 时,没有数据可以读取。在尝试从中读取数据之前,您需要使用fseek 返回文件的开头。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 2023-02-05
        • 2015-09-12
        • 1970-01-01
        • 2011-09-14
        • 2021-10-20
        相关资源
        最近更新 更多