Search code examples
c++binaryistream

Reading from a file byte per byte C++


Im trying to write a program in C++ that will take 2 files and compare them byte by byte.

I was looking at the following post

Reading binary istream byte by byte

Im not really sure about parts of this. When using get(char& c) it reads in a char and stores it in c. Is this storing as, say 0x0D, or is it storing the actual char value "c" (or whatever)?

If i wish to use this method to compare two files byte by byte would i just use get(char& c) on both then compare the chars that were got, or do i need to cast to byte?

(I figured starting a new post would be better since the original is quite an old one)


Solution

  • chars are nothing but a "special type of storage" (excuse the expression) for integers, in memory there is no difference between 'A' and the decimal value 65 (ASCII assumed).

    c will in other words contain the read byte from the file.


    To answer your added question; no, there is no cast required doing c1 == c2 will be just fine.


      char c1 = 'A', c2 = 97, c3 = 0x42; 
    
      std::cout <<  c1  << "  " <<    c2 << "  " <<    c3 << std::endl;
      std::cout << +c1  << " "  <<   +c2 << " "  <<   +c3 << std::endl;
    

    /* Writing +c1 in the above will cast c1 to an int, it's is the same thing as writing (int)c1 or the more correct (c++ish) static_cast<int> (c1). */

    output:

    A  a  B
    65 97 66