c0da
c0da

Reputation: 1009

C++ Binary file read issue

I was making a function to read a file containing some dumped data (sequence of 1 byte values). As the dumped values were 1 byte each, I read them as chars. I opened the file in binary mode, read the data as chars and did a casting into int (so I get the ascii codes). But the data read isn't correct (compared in a hex-editor). Here's my code:

int** read_data(char* filename, int** data, int& height, int& width)
{
    data=new int*[height];
    int row,col;
    ifstream infile;
    infile.open(filename,ios::binary|ios::in);
    if(!infile.good())
    {
        return 0;
    }
    char* ch= new char[width];
    for(row=0; row<height; row++)
    {
        data[row]=new int[width];
        infile.read(ch,width);
        for(col=0; col<width; col++)
        {
            data[row][col]=int(ch[col]);
            cout<<data[row][col]<<" ";
        }
        cout<<endl;
    }
    infile.close();
    return data;
}

Any ideas what might be wrong with this code? My machine is windows, I'm using Visual Studio 2005 and the (exact) filename that i passed is:

"D:\\files\\output.dat"

EDIT: If I don't use unsigned char, the first 8 values, which are all 245, are read as -11.

Upvotes: 3

Views: 765

Answers (3)

Bo Persson
Bo Persson

Reputation: 92381

A plain char can be either signed or unsigned, depending on the compiler. To get a consistent (and correct) result, you can cast the value to unsigned char before assigning to the int.

data[row][col]=static_cast<unsigned char>(ch[col]);

Upvotes: 0

eugene_che
eugene_che

Reputation: 1997

Your error seems to cover in using of char* for ch. When you try to output it, all chars are printed until the first zero value.

Upvotes: 1

Kocki
Kocki

Reputation: 123

I think, you might have to use unsigned char and unsigned int to get correct results. In your code, the bytes you read are interpreted as signed values. I assume you did not intend that.

Upvotes: 3

Related Questions