A question about writing binary data

This is the program that implements a binary highscore file. Notice in the end of the program
1
2
3
4
5
for (vector<int>::iterator itr = score.begin(); itr != score.end(); itr++)
    {
        int temp = *itr;
        file.write(reinterpret_cast<char*>(&temp), sizeof(temp));
    }


if i replace it by:
1
2
3
4
for (vector<int>::iterator itr = score.begin(); itr != score.end(); itr++)
    {
        file.write(reinterpret_cast<char*>(itr), sizeof(*itr));
    }

it's turn out that the program cant compile. and when i change to this
file.write(reinterpret_cast<char*>(*itr), sizeof(*itr));
its compiled but if i try to input a not-in-order list, the program crashs
i want to know what the problem is. thank

Here is the full .cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    fstream file("highscores.bin", ios::in | ios::out | ios:: binary);
    if (!file.is_open())
    {
        cout << "File open error!\n";
        return 0;
    }
    int input_score, read_score;
    cout << "Input score: ";
    cin >> input_score;
    streampos pre_pos = file.tellg();
    while (file.read(reinterpret_cast<char*>(&read_score), sizeof(read_score)))
    {
        if (input_score > read_score)
        {
            break;
        }
        pre_pos = file.tellg();
    }
    if (file.fail() && ! file.eof())
    {
        cout << "Bad input.\n";
        return 0;
    }
    file.clear();
    file.seekg(pre_pos);
    vector<int> score;
    while (file.read(reinterpret_cast<char*>(&read_score), sizeof(read_score)))
    {
        score.push_back(read_score);
    }
    if (!file.eof())
    {
        cout << "Reading failed!\n";
        return 0;
    }
    file.clear();
    file.seekp(pre_pos);
    file.write(reinterpret_cast<char*>(&input_score), sizeof(input_score));
    for (vector<int>::iterator itr = score.begin(); itr != score.end(); itr++)
    {
        int temp = *itr;
        file.write(reinterpret_cast<char*>(&temp), sizeof(temp));
    }
}
Last edited on
itr is an iterator, it represents a place in a file not a printable character. Casting it to a char pointer or casting it's value to a char pointer doesn't magically make it printable.
1
2
3
4
5
for (vector<int>::iterator itr = score.begin(); itr != score.end(); itr++)
    {
        int temp = *itr;
        file.write(reinterpret_cast<char*>(&temp), sizeof(temp));
    }

Here they are dereferencing the iterator and storing that value as an integer then on the next line they are casting the reference to that integer it to a char pointer.
Last edited on
Topic archived. No new replies allowed.