5

I have opened a file in binary mode, and doing below operations gives negative value of x. The file that I have opened is ~2.5 GB in size.

infile.seekg(0, ios::end);
__int64 x = infile.tellg();

I needed infile to read bytes (unsigned chars), so I had defined it as a uifstream by doing:

typedef basic_ifstream<unsigned char, std::char_traits<unsigned char> > uifstream;

which is basically a standard ifstream, but with unsigned chars instead of chars.

EDIT: I am using Visual Studio 2005 and corrected uofstream to uifstream.

c0da
  • 1,009
  • 3
  • 14
  • 28
  • Are you using an output stream as input? `seekg` and `tellg` does only exist in input file streams. – Some programmer dude Nov 04 '11 at 09:28
  • oops.. that was a typo... corrected it now... – c0da Nov 04 '11 at 09:31
  • How did you opened the file? which options you used? Is correctly opened? Did you checked internal status flags after opening and seekg? – Tio Pepe Nov 04 '11 at 09:33
  • found something on this link, but couldn't find any solution... There is something about the 2^31 limit... http://www.velocityreviews.com/forums/t686780-can-ifstream-read-file-more-than-2g.html – c0da Nov 04 '11 at 09:34
  • opened the file using `ios::in | ios::binary` flags... And yes, I do a `infile.is_good()` check before which confirms that the file is open... – c0da Nov 04 '11 at 09:36
  • Maybe the implementation of the standard library uses a signed 32-bit type for the position type? – Some programmer dude Nov 04 '11 at 09:41
  • by the way, I used Visual Studio's `_stat64` function to get the file size, which returns the correct file size... but the question still remains that what is the problem with seekg() and tellg() here... – c0da Nov 04 '11 at 09:42
  • 2
    STL in VS2005 does not support large offsets, see: http://stackoverflow.com/questions/4404760/processing-files-larger-than-2-gb-in-c-with-stl – rve Nov 04 '11 at 09:45

2 Answers2

6

I already put this in a comment but I think it is also the answer:

STL in VS2005 does not support offsets larger than 2147483647 (~2GB) so seeking or telling the position beyond that does not work and would explain the negative values. (see here)

(Also tellg() returns -1 when there is an error, but I assume you are seeing other negative values)

The solution is to use a newer compiler (VS2010) or use an alternative STL implementation like STLPort

Community
  • 1
  • 1
rve
  • 5,897
  • 3
  • 40
  • 64
0

Here is a dirty VS2010-compatible solution:

__int64 size = *(__int64*) ( ((char*)&(infile.tellg())) +8)
Stepan Yakovenko
  • 8,670
  • 28
  • 113
  • 206