1

We are reading into a file by accessing it through a std::ifstream, let's call it ifs. In our current procedure, we make a few formatted input operations (i.e. using operator>>()), which leads us to a given position in the stream, let's call it posA

Then, want to re-read from the beginning of the file until posA in a char buffer. To achieve this, we make an unformatted input opeation (using read()).

Our naïve approach

What we were doing under Unix OSes was to initialize posA with the value from tellg(), then convert use it as the integral value offset from the beginning of the file:

(simplified code)

// several formatted input operations
std::istream::pos_type posA = ifs.tellg(); 
ifs.seekg(0); // rewind to the beginning of the stream
ifs.read(buffer, posA);

Sadly, when porting the code we discovered that the pos_type returned by tellg() is not necessarily the byte offset from the beginning of the stream (see also this SO answer).

The question

Which leads us to the question: is there a portable way to get the current position in an input stream (or at least an std::ifstream) as the number of bytes from the beginning of the stream/file ? (So this value could notably be used to read() the bytes from the beginning until this exact position).

Community
  • 1
  • 1
Ad N
  • 7,930
  • 6
  • 36
  • 80

1 Answers1

0

The only resort is to open the file in binary mode, e.g. std::ifstream f{filename, std::ios_base::binary};.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271