我正在使用Linux和C ++。 我有一个大小为210732字节的二进制文件,但用seekg / tellg报告的大小是210728。
我从ls-la获得以下信息,即210732字节:
-rw-rw-r– 1 pjs pjs 210732 Feb 17 10:25 output.osr
并用下面的代码片段,我得到210728:
std::ifstream handle; handle.open("output.osr", std::ios::binary | std::ios::in); handle.seekg(0, std::ios::end); std::cout << "file size:" << static_cast<unsigned int>(handle.tellg()) << std::endl;
所以我的代码closures了4个字节。 我已经用hex编辑器确认文件的大小是正确的。 那为什么我没有得到正确的尺寸?
我的回答:我认为这个问题是由于有多个开放的fstreams文件。 至less这似乎已经整理出来了。 感谢所有帮助过我的人。
至少对于我在64位CentOS 5上使用G ++ 4.1和4.4,下面的代码是按照预期工作的,即程序打印的长度与stat()调用返回的长度相同。
#include <iostream> #include <fstream> using namespace std; int main () { int length; ifstream is; is.open ("test.txt", ios::binary | std::ios::in); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); cout << "Length: " << length << "\nThe following should be zero: " << is.tellg() << "\n"; return 0; }
你为什么打开文件并检查大小? 最简单的方法是做这样的事情:
#include <sys / types.h> #include <sys / stat.h> off_t getFilesize(const char * path){ struct stat fStat; if(!stat(path,&fStat))返回fStat.st_size; 其他perror(“文件Stat失败”); }
编辑:谢谢PSJ指出一个小错字故障… 🙂
当有Unix的味道的时候,为什么我们使用这个,当我们有stat的时候
long findSize( const char *filename ) { struct stat statbuf; if ( stat( filename, &statbuf ) == 0 ) { return statbuf.st_size; } else { return 0; } }
如果不,
long findSize( const char *filename ) { long l,m; ifstream file (filename, ios::in|ios::binary ); l = file.tellg(); file.seekg ( 0, ios::end ); m = file.tellg(); file.close(); return ( m – l ); }
ls -la实际上是报告文件在磁盘上占用的字节数,而不是实际大小? 这可以解释为什么它略高。