在为大量字节读取文件时,我在Visual Studio 2015上发现了以下奇怪的行为。我加载的文件大约是80 MB,足够大。
#include <cstdio>
#include <vector>
int main() {
std::FILE* file;
errno_t error = _wfopen_s(&file, L"/User/account/Desktop/file.data", L"r");
const std::size_t n = 16384;
std::vector<unsigned char> v(n);
const std::size_t nb_bytes_read = std::fread(v.data(), sizeof(unsigned char), n, file);
// At this point error = 0 and nb_bytes_read = 3473
}
所以我问std::fread
16384字节,即使文件足够大,它也只给我3473。它应该被视为一个错误吗?标准似乎没有这么说,但这种行为对我来说非常奇怪。
答案 0 :(得分:3)
尝试以二进制模式"rb"
打开文件,这无论如何都是你想要的。否则,在Windows平台上the byte \0x1A
terminates input。此外,\r\n
之类的换行符也会转换为\n
,这也可能导致读取的字节数少于指定值。
答案 1 :(得分:2)
根据this reference,如果达到EOF或发生错误,fread()
将仅返回少于请求的字节数。您可以查看feof()
和ferror()
。