Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 461
RagHaven Avatar asked Jul 26 '13 08:07

RagHaven


2 Answers

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]<<" ";
like image 129
P0W Avatar answered Sep 19 '22 21:09

P0W


What you see is valid and normal behavior when you print non-printable characters like ASCII - 5,10,15,20,25. It looks different when they are printed as character. So either you can try with cast to int or you can try with printable character (char) like A, B, C, D, E

Your code could behave as expected with,

1) Assigning printable characters,

    unsigned char data[5]={'A','B','C','D','E'};

or

2) Casting the output to int,

    for(int i=0; i<5;i++)
       cout<< (int) data2[i]<<" ";
like image 26
VoidPointer Avatar answered Sep 21 '22 21:09

VoidPointer