C ++:获取不正确的文件大小 [英] C++: Getting incorrect file size
问题描述
我使用的是Linux和C ++。我有一个大小为210732字节的二进制文件,但是与seekg / tellg报告的大小是210728。
I'm using Linux and C++. I have a binary file with a size of 210732 bytes, but the size reported with seekg/tellg is 210728.
我从ls-la获得以下信息, 210732个字节:
I get the following information from ls-la, i.e., 210732 bytes:
-rw-rw-r-- 1 pjs pjs 210732 Feb 17 10:25 output.osr
-rw-rw-r-- 1 pjs pjs 210732 Feb 17 10:25 output.osr
使用下面的代码片段,我得到210728:
And with the following code snippet, I get 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;
所以我的代码关闭了4个字节。我已经确认文件的大小是正确的十六进制编辑器。那么为什么我得不到正确的大小?
So my code is off by 4 bytes. I have confirmed that the size of the file is correct with a hex editor. So why am I not getting the correct size?
我的回答:我认为这个问题是由于有多个打开fstreams的文件。至少,似乎已经整理出来了我。感谢所有帮助过的人。
推荐答案
至少对于64位CentOS 5上的G ++ 4.1和4.4 ,下面的代码按预期工作,即程序打印输出的长度与stat()调用返回的长度相同。
At least for me with G++ 4.1 and 4.4 on 64-bit CentOS 5, the code below works as expected, i.e. the length the program prints out is the same as that returned by the stat() call.
#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;
}
这篇关于C ++:获取不正确的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!