unexpected output from binary file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void read () {
    int buff;
    fstream bin ("fails.bin", ios::in);
    while (bin) {
        bin.read ((char*)&buff, sizeof(int));
        cout<<"status: "<<buff<<endl;
        bin.read ((char*)&buff, sizeof(int));
        cout<<"gads: "<<buff<<endl;
        bin.read ((char*)&buff, sizeof(int));
        cout<<"menesis: "<<buff<<endl;
        bin.read ((char*)&buff, sizeof(int));
        cout<<"diena: "<<buff<<endl<<endl;
    }
    bin.close();
}


output:

.................
............

status: 0
gads: 126121
menesis: 5
diena: 8

status: 0
gads: 11
menesis: 9
diena: 3

status: 3
gads: 3
menesis: 3
diena: 3



Why does it produces last output with numbers 3, shouldn't while (bin) {.....} stop it since file ends?
Nope, because you haven't had an unsuccessful read yet. You need to check the return of bin.read(), which returns *this.

1
2
3
while( bin.read( (char*)&buff, sizeof(int) ) ) {
    //...
}

1
2
3
while( bin.read( (char*)&buff, sizeof(int) ) ) {
    //...
}

messed up my output since it was moving current position in file with that while so i did this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void read () {
    int buff;
    fstream bin ("fails.bin", ios::in);
    while (bin.read( (char*)&buff, sizeof(int) )) {
        bin.seekg(-4, ios::cur);                                 //added this line
        bin.read ((char*)&buff, sizeof(int));
        cout<<"status: "<<buff<<endl;
        bin.read ((char*)&buff, sizeof(int));
        cout<<"gads: "<<buff<<endl;
        bin.read ((char*)&buff, sizeof(int));
        cout<<"menesis: "<<buff<<endl;
        bin.read ((char*)&buff, sizeof(int));
        cout<<"diena: "<<buff<<endl<<endl;

    }
    bin.close();
}

it seems it works so far as its supposed to.
my question is...can i write it in some other way?
Use a struct of 4 ints and read all four ints in at once into the struct rather than one int at a time.

You ought to be careful when dealing with binary data though. Portable solutions have to take into account struct packing and endianness issues.
Topic archived. No new replies allowed.