I'm trying to get BITMAPFILEHEADER part from .bmp file. I expected to see some numbers, but have ASCII symbols. How to solve this problem?
std::string path;
std::ifstream file;
path = "C:\\Users\\user\\Desktop\\Emp.bmp";
file.open(path);
if (!file.is_open())
{
std::cout << "ERROR";
}
else
{
char fromfile[14];
file.read(fromfile, 14);
std::cout << fromfile;
file.close();
}
I tried to translate ASCII output to HEX-symbols and I have correct data (It matches with HEX-editor data), but I can't understand why I get ASCII from program output
This line:
std::cout << fromfile;
Treats fromfile
as if it was a null-terminated string, because it is an array of char
s.
If you want to see the numeric value of the bytes, you can use:
for (auto const & c : fromfile)
{
std::cout << static_cast<int>(c) << ", ";
}
If you want to see only positive values (since char
can be signed), the loop body should be:
std::cout << static_cast<int>(static_cast<unsigned char>(c)) << ", ";
And if you want hex values replace it with:
std::cout << std::hex << static_cast<int>(static_cast<unsigned char>(c)) << ", ";
Another issue is that you open the file in text mode (the default), instead of opening it in binary mode which is more suited for your purpose:
//--------------vvvvvvvvvvvvvvvv-
file.open(path, std::ios::binary);