我正在阅读这样的 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
,返回值应该是读取的字节数。 最佳答案
试试这个:
//byteCount = fread(filecontents, filesize, 1, fh);
byteCount = fread(filecontents, 1, filesize, fh);
关于c - fread 返回值 1 字节,即使文件被完全读取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15440671/