我正在使用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;
Run Code Online (Sandbox Code Playgroud)
所以我的代码关闭了4个字节.我已使用十六进制编辑器确认文件的大小是正确的.那么为什么我没有得到正确的尺寸?
我的回答:我认为这个问题是由于文件中有多个开放的fstream引起的.至少那似乎已经为我解决了.感谢所有帮助过的人.
你为什么打开文件并检查大小?最简单的方法是这样做:
#include <sys/types.h>
#include <sys/stat.h>
off_t getFilesize(const char *path){
struct stat fStat;
if (!stat(path, &fStat)) return fStat.st_size;
else perror("file Stat failed");
}
编辑:感谢PSJ指出一个小错字故障...... :)
至少对于我在 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;
}
Run Code Online (Sandbox Code Playgroud)