I read a file with std::ifstream
into an std::vector< char >
, and would like to print each char as a hexadecimal value. I can do this with printf
but would prefer to do it with std::cout
in an elegant way:
std::ifstream ifs( "myfile", std::ios::binary | std::ios::ate );
std::ifstream::pos_type pos = ifs.tellg();
std::vector< char > buffer( pos );
ifs.seekg( 0, std::ios::beg );
ifs.read( buffer.data(), pos );
// File contents loaded perfectly
printf( "%02hhx", buffer[ 1234 ] );
// Prints what I want but not modern C++
std::cout << std::hex << std::fill( '0' ) << std::setw( 2 ) << buffer[ 1234 ];
// Modern C++ but does not print what I want (e.g. if `buffer[ 1234 ]` is 65, an A appears)
std::cout << std::hex << std::fill( '0' ) << std::setw( 2 )
<< static_cast< int >( *reinterpret_cast< const unsigned char* >( &buffer[ 1234 ] ) );
// Modern C++ and prints what I want. But what about neatness and elegance?