fread返回值1个字节,即使文件已完全读取

时间:2013-03-15 19:31:40

标签: c file-io

我正在读这样的tarfile:

fh = fopen(filename, "r");

if (fh == NULL) {
    printf("Unable to open %s.\n", filename);
    printf("Exiting.\n");
    return 1;
}

fseek(fh, 0L, SEEK_END);
filesize = ftell(fh);
fseek(fh, 0L, SEEK_SET);

filecontents = (char*)malloc(filesize + 1);     // +1 for null terminator

byteCount = fread(filecontents, filesize, 1, fh);
filecontents[filesize] = 0; 

fclose(fh);

if (byteCount != filesize) {
    printf("Error reading %s.\n", filename);
    printf("Expected filesize: %ld bytes.\n", filesize);
    printf("Bytes read: %d bytes.\n", byteCount);
}

然后我继续解码tarfile的内容并提取存储在其中的文件。一切正常,文件提取得很好,但fread()正在返回1而不是filesize。我得到的输出是:

Error reading readme.tar.
Expected filesize: 10240 bytes.
Bytes read: 1 bytes.

根据CPP Reference on fread,返回值应该是读取的字节数。

1 个答案:

答案 0 :(得分:11)

试试这个:

//byteCount = fread(filecontents, filesize, 1, fh);
byteCount = fread(filecontents, 1, filesize, fh);