I want to open a gif file from the laptop and read it byte by byte to read the header and other sources contained in a file. I opened a file using the code below:
#include <iostream>
#include <fstream>
#include <cstdint>
#include <vector>
#include <iomanip>
int main()
{
// define a byte as an octet (an unsigned 8-bit value)
using byte = std::uint8_t ;
constchar file_name[] = __FILE__ ; // this file
// try to open the file for input, in binary mode
if( std::ifstream file{ file_name, std::ios::binary } )
{
// if opened successfully,
// try to read in the first 50 bytes (as characters)
const std::size_t nbytes = 50 ;
std::vector<char> buff(nbytes) ; // allocate a buffer of nbytes characters
if( file.read( buff.data(), buff.size() ) ) // try to read in nbytes
{
constauto nread = file.gcount() ; // number of bytes that were actually read
// from the characters that were read, initialise a vector of nbytes bytes
std::vector<byte> bytes( buff.begin(), buff.begin() + nread ) ;
// print out the values of the bytes (two hex digits per byte)
std::cout << "the first " << nbytes << " bytes in the file '"
<< file_name << "' are hex:\n" << std::setfill('0') ;
for( byte b : bytes ) std::cout << std::hex << std::setw(2) << int(b) << ' ' ;
std::cout << '\n' ;
}
}
}