Search code examples
c++cfile-iofwritefread

Writing and reading unsigned chars to binary file


I am writing a simple program that writes to a binary file, closes it and then reads the data that was just written. I am trying to write an array of unsigned characters. I am experiencing some issues while reading the data. I am not exactly sure if I am writing the data improperly or reading it wrong. When I read the data I get my output as: 5 bytes for the number of bytes read, but the output I got was not the same as the values I had wrote to the file.

FILE *binFile = fopen("sample","wb");

unsigned char data[5]={5,10,15,20,25};
fwrite(data,sizeof(unsigned char),sizeof(data),binFile);
fclose(binFile);

unsigned char data2[5];
binFile = fopen("sample","rb");
int s = fread(data2,1,sizeof(data),binFile);
fclose(binFile);
cout<<s<<" bytes\n";
for(int i=0; i<5;i++)
        cout<<data2[i]<<" ";
cout<<"\n";

Solution

  • What you are receiving as output seeing are ASCII characters of elements of array

    Typecast unsigned char to int

    This will give expected output.

    for(int i=0; i<5;i++)
            cout<<(int)data2[i]<<" ";