【发布时间】:2012-10-09 01:49:06
【问题描述】:
关于如何测量文件大小的几个主题(参见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;
}
它会起作用吗?如果不是,为什么?
【问题讨论】:
-
只是一个旁注,对
close的调用是不必要的。 -
可能会起作用,但不确定这是获取文件大小的最佳方法。
-
如果我需要获取文件大小,我通常会这样调用:
std::ifstream file( filepath, std::ios::ate | std::ios::binary);int fileLength = 0;file.seekg(0, std::ios::end);fileLength = file.tellg();file.seekg(0, std::ios::beg);if(fileLength == -1) { //error stuff here}等等。我相信流位置的差异,它是一个内部字符数组,所以位置 1,可以偏移 0。虽然,这部分我并不积极 -
@SethCarnegie:为什么不需要关闭电话?
-
因为
ifstream是一个RAII对象,当它被销毁时会关闭它的文件。
标签: c++ file size fstream standard-library