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.
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
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;
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?
My answer: I think the problem was caused by having multiple open fstreams to the file. At least that seems to have sorted it out for me. Thanks to everyone who helped.
Why are you opening the file and checking the size? The easiest way is to do it something like this:
#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"); }
Edit: Thanks PSJ for pointing out a minor typo glitch... :)
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;
}
When on a flavour of Unix, why do we use that, when we have the stat utlilty
long findSize( const char *filename )
{
struct stat statbuf;
if ( stat( filename, &statbuf ) == 0 )
{
return statbuf.st_size;
}
else
{
return 0;
}
}
if not,
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With