tags:

views:

152

answers:

2

Is there a better way to determine the length of an std::istream than the following:

std::istream* pcStream = GetSomeStream();
pcStream->seekg(0, ios::end);
unsigned int uiLength = pcStream->tellg();

It just seems really wasteful to have to seek to the end of the stream and then seek back to the original position, especially if the stream might be to a file on some slow media like a CD or DVD.

+2  A: 

The "best" way is to avoid needing the length :)

  • Not all streams are seekable (For example, imagine an istream on a network socket)
  • The return type from tellg() is not necessarily numeric (the only requirement is that it can be passed back to seekg() to return to the same position)
  • Even if it is numeric, it is not necessarily a number of bytes. For example, it could be a "magic" value meaning "at the end"
  • For fstreams, issues like case and linefeed conversion can screw things up
Éric Malenfant
I do realize expecting a length to always be available is a bit limiting to the kind of streams to be used, thankfully it's very unlikely I'll be using anything other then ifstreams and my own memstream and zipstream implementations.
FlintZA
A: 

Have you considered keeping track of the size by using istream::gcount() ?

Marcin
I require the size for allocation of the buffer to which the data will be copied-I suppose I could allocate an initial amount and realloc thereafter, but I'm a bit worried about fragmentation (working in a limited mem environment).
FlintZA