3

我浏览了手册页,并在线阅读了一些示例。我所有其他系统和标准调用似乎都在处理相同的数据,为什么不 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;
}
4

2 回答 2

3

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

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

fseek(fp, 0L, SEEK_SET);

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

rewind(fp);
于 2011-12-12T23:13:52.743 回答
1

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

于 2011-12-12T23:13:05.340 回答