user3861918
user3861918

Reputation:

binary input output problems

i am trying to learn how binary file works . When i input anything above 127 its giving me wrong answer . Please explain me why this happening ..

int x[10] = {124,45,21,35,45,25,26,254,12,32};

fstream BCD("Random.bin", ios::binary | ios::out  | ios::trunc);

if (!BCD.is_open()) {
    cout << "opps<<";

}
else
{
    for (int i = 0; i < 10; i++) {
        BCD.put(x[i]);
    }

}
BCD.close();

 int out[10];
fstream file("Random.bin", ios::binary | ios::in);

 char C;
int i = 0;
while (file.good())
{
    file.get(C);
    out[i] = ( int)C ;
    i++;
}

i just want store some value in between 0 - 255 as binary and read back and How can i get a file size if i accessing some file is there any way to find its size first and read data based on the size. I only know one way that is in the above code a don't know i am doing correct or not plz correct me if i am wrong

Upvotes: 0

Views: 74

Answers (1)

mksteve
mksteve

Reputation: 13085

The problem is when reading, the value is being treated as signed, or negative. You need to use :-

char C;
int i = 0;
while (file.good())
{
    file.get(C);
    if( file.good() ){
        out[i] = static_cast<int>( static_cast<unsigned char>( C ) );
        i++;
    }
}

Unfortunately as I thought earlier fstream::get takes char only, so we need it to be a char.

So we read it as a char, then reinterpret it as unsigned char.

Finally replace the C cast (int) as a C++ cast static_cast to get to an integer value (signed, but positive).

There also needs to be a check to ensure that the buffer is not overrun, when reading beyond the last element

Upvotes: 1

Related Questions