seekg() not working properly, sets the pointer in wrong places.

So, here's the code that shows what my current problem is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    ofstream t;
    t.open(mainTape.c_str());
    t << 1.0 << ',' << 3.1 << ',' << 1.0 << '|';
    t << 1.0 << ',' << 3.2 << ',' << 1.0 << '|';
    t << 1.0 << ',' << 3.3 << ',' << 1.0 << '|';
    t << 1.0 << ',' << 3.4 << ',' << 1.0 << '|';
    t << 1.0 << ',' << 3.5 << ',' << 1.0 << '|';
    t.flush();
    t.close();
    
    ifstream i;
    i.open(mainTape.c_str());
    float a,b,c;
    char g;
 
    i.seekg((3*sizeof(float) + 3*sizeof(char))); // THERE

    i >> a >> g >> b >> g >> c >> g;
    cout << a << ' ' << b << ' ' << c << ' '  << endl;
    
    i.seekg(-1*(3*sizeof(float) + 3*sizeof(char)));
    
    i >> a >> g >> b >> g >> c >> g;
    cout << a << ' ' << b << ' ' << c << ' '  << endl;
    
    i.close();


WHat I'm trying to do is rather simple: Write a few values to a file, separated by commas and '|'. Read the second set of values from the file, print it to the screen, go back in a file, read the same values again, and print them to the screen again.

And then there's that place in the code, bookmarked by a 'THERE' comment.

The code works OK if i remove that line. All the values are printed OK. But once that line's there, all I see is zero'es. It doesn't read from file properly. Why's that? How can I fix it?

I'd really, really be grateful if someone could help me with that one!
You're trying to see across text data as if it were binary data. You can't do that.

Typically speaking, seekg only works with binary data. it can also work with text data provided you know the number of characters that exist in the strings you want to seek over -- but usually you don't.

sizeof(float) and seekg() both work on the size in bytes. They don't work on the textual representation in characters. For example, sizeof(float) is 4 bytes on most machines, but the text in your file is only 3 characters.
Ok, thanks for the tip, however, it's still problematic. If i open these two files using ios_base::binary, I can't really use streams there. At least, I think, because after adding the necessary flags, the code still doesn't work. Any tips on how to fix that?
all ios_base::text does is translate line breaks. Whether your use ios_base::binary or text here doesn't matter for this particular problem.

The data is text. This is because you're using the insertion/extraction operators (<<, >>) which convert to/from text.

You have two options:

1) Keep the file as text, but don't use seekg. Instead, to seek forward, you would need to read/extract data and throw it away

or

2) Make the file binary, don't use <<, >>, and instead use read()/write(). If you do this, you must open the file in ios_base::binary as well.
Topic archived. No new replies allowed.