seekg or seekp

So, I have a binary file that contains char array information than float information. And I need to read and sum only the float numbers. How can I jump the char bytes and land where there is another float? I'm trying to use that seekp or seekg but I don't have too much skills with there commands.


1
2
3
4
5
6
7
8
9
10

ifstream archive("name.bin", ios::binary);

float value;
float total = 0;
while(!(archive.eof())){//while the archive does not reach the end keep on
    //first jump the char[20] arr than:
    archive.read(reinterpret_cast<char*>(&value), sizeof(float));
    total += value;
}


Thanks!!
Last edited on
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;
  }
  // ...
}

Last edited on
Thanks!
Just another detail, if I have a char array[20], and each time the user input a different string(meaning that wont use the same amount of space always). If I ignore(20) will always work? the file may be like that:

water
60
car
9
street
777
headphone
1
I can't really say for sure without the code which actually writes the file. It's simplest to always write the complete array every time, e.g., with
 
archive.write(my_c_string, 20);

In which case ignore(20) will always work, yes.

There are, naturally, other ways to do this. The answer depends on how you have done it.
Registered users can post here. Sign in or register to post.