有关如何测量文件大小的几个主题(请参阅Using C++ filestreams (fstream), how can you determine the size of a file?和C++: Getting incorrect file size)计算文件开头和结尾之间的差异,如下所示:
std::streampos fileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}但是,我们可以在最后打开文件,而不是在开始时打开文件,然后采取如下措施:
std::streampos fileSize( const char* filePath ){
std::ifstream file( filePath, std::ios::ate | std::ios::binary );
std::streampos fsize = file.tellg();
file.close();
return fsize;
}它会起作用吗?如果不是,为什么呢?
发布于 2012-10-09 10:04:35
它应该工作得很好。关于std::ios::ate,C++标准规定了
ate-打开并在打开后立即结束
当手动打开然后查找会成功时,它没有理由会失败。无论哪种情况,tellg都是一样的。
https://stackoverflow.com/questions/12791807
复制相似问题