[HELP] how to read a file byte by byte

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:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{

  //Programme title
  cout << "GIF IMAGE VIEWER\n" << endl;

  //Opening File
  ifstream gif;
  string filename;

  cout << "Enter file name: " << endl;
  getline (cin,filename);
  cout <<""<< endl;

  gif.open (filename.c_str());

}



From the file that I brought from the laptop, is it going to read in hexadecimal? And how can I read it byte by byte?
Last edited on
Something along these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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 ;

    const char 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
        {
            const auto 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' ;
        }
    }
}

http://coliru.stacked-crooked.com/a/34903a3845fc9052
Topic archived. No new replies allowed.