To ignore some number of bytes, call
ignore() instead.
http://en.cppreference.com/w/cpp/io/basic_istream/ignore
If seeking is necessary, since your intent is to
get information from the file, seek the
get pointer using
seekg(). seekp moves the
put pointer, for putting data into the file.
Also, try to avoid looping on
eof()
. It's usually wrong.
This particular input loop exhibits potential undefined behavior, or at least causes the last record to be processed twice. This is because
eof() doesn't tell you if you are at the end-of-file. It only tells you if you have attempted to read past the end already.
Instead, perform any I/O operations as the loop condition. If the input operation fails because the stream entered an error state, no information will be processed.
One way to write this is as follows:
1 2 3 4 5 6 7 8 9 10 11 12
|
// TODO: choose a better name
// TODO: eliminate the magic number 20
static std::istream& read_partial_record(std::istream &s, float &f)
{ return s.ignore(20) && s.read(reinterpret_cast<char*>(&f), sizeof f); }
int main() {
// ...
for (float f = 0.f; read_partial_record(archive, f); ) {
total += f;
}
// ...
}
|