Read binary file byte by byte
I have this weird assignment in my C++ class where I must write a certain number in a binary file (132.147), using the float type, and then read it, using the char type, in such a way that the final result would be the decimal value of each byte (-94, 37, 4 and 67).
fstream binFile("blah.bin", ios::binary|ios::in|ios::out); float a = 132.147; binFile.write((char*)&a, sizeof(float)); char b; binFile.read((char*)&b, sizeof(b)); cout << (int)b << ' ' << (int)b << ' ' << (int)b << ' ' << (int)b << endl; // -51 -51 -51 -51 cout << b << ' ' << b << ' ' << b << ' ' << b; // = = = = binFile.close(); return 0;
I understand where they got those 4 numbers from. If I write the file and read it using an hex editor, I get 4 hexadecimal numbers that, once converted to a signed binary can then be converted to their decimal form. However, I have absolutely no clue how I can programatically do this in C++. Any clue?
As Adam says you must reopen the file. You might have noticed it wasn't reading if you'd checked the return value from read. You only need to read sizoef a bytes, but asking to read more is harmless. After you read b...
cout << (int)b << ' ' << ...