Reputation: 4028
I'm modifying a reading routine for binary data. Unfortunately I'm not that firm in C++ anymore, which is the language the routine is written in. The routine starts reading some data. After that I want it to look at a buffered value which I also read from the file. Depending on the value the code should either do something and continue normally afterwards or undo reading the buffer and continue normally.
My problem is the undoing or reverting the cursor position, if you will. The stripped code looks something like this:
int buffer;
std::fstream inputFile;
inputFile.open( "Filename", std::ios::in | std::ios::binary );
... // read some data from inputFile
// read buffer value
inputFile.read( reinterpret_cast<char *>(&buffer), sizeof(buffer) );
if( buffer == 256 ) {
... // do something here
} else
// make it so nothing (including reading the buffer earlier) happened
inputFile.seekg( -1*sizeof(buffer), std::ios::cur ); // <---- is this right?
// or do I need to do it this way?
inputFile.seekg( -1*sizeof(buffer)/sizeof(char), std::ios:cur );
}
I assume I can use negative values in seekg()
as I find int only logicall and haven't read anything to the contrary. Which way above is correct? Or basically I'm asking what does seekg()
actually expect as first argument?
The C++ Reference only says this:
istream& seekg (streamoff off, ios_base::seekdir way); off Offset value, relative to the way parameter. streamoff is an offset type (generally, a signed integral type). way Object of type ios_base::seekdir. It may take any of the following constant values: value offset is relative to... ios_base::beg beginning of the stream ios_base::cur current position in the stream ios_base::end end of the stream
Which doesn't tell me the unit off
is measured in (bytes, chars, ints?).
Upvotes: 1
Views: 1054
Reputation: 153895
The version of seekg()
taking a whence
argument takes an std::streamoff
as argument. It can be negative. There is no need to divide by sizeof(char)
as sizeof(char)
is defined to be 1
. Since stream aleays operate on characters, the units used by streams are characters, i.e., the type of the first template argument of the stream.
Upvotes: 1