Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Getting incorrect file size

Tags:

c++

linux

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.

like image 1000
PSJ Avatar asked Feb 17 '10 16:02

PSJ


3 Answers

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... :)

like image 87
t0mm13b Avatar answered Sep 23 '22 22:09

t0mm13b


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;
}
like image 38
janneb Avatar answered Sep 22 '22 22:09

janneb


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 );
}
like image 42
Narendra N Avatar answered Sep 23 '22 22:09

Narendra N