使用以下函数获取文件大小时,可能得到返回值为 2
size_t size_of_file(const std::string& filename)
{
std::ifstream file(filename, std::ios::binary);
file.seekg(std::ios::end);
return file.tellg();
}
2 是 std::ios::eofbit 的值。
解决方法有二
size_t size_of_file(const std::string& filename)
{
std::ifstream file(filename, std::ios::binary | std::ios::ate);
return file.tellg();
}
或者
size_t size_of_file(const std::string& filename)
{
std::ifstream file(filename, std::ios::binary);
file.seekg(0, std::ios::end);
return file.tellg();
}