discodowney
discodowney

Reputation: 1507

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)

Upvotes: 0

Views: 1641

Answers (2)

Filip Roséen
Filip Roséen

Reputation: 63882

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

Upvotes: 2

Stefan
Stefan

Reputation: 2613

Ehm,

a char contains 1 Byte The interpretation of that value is indeed depending on you, the programmer.

If you print that byte in the cout stream it is interpreted via ASCII Code and therefor if your char was 0x63 then it will print 'c' on the screen.

If you just use the value you can use it as you like..

char c = 0x63;
c++;
// c is now: 0x64

Note that you can also input decimals

Upvotes: 0

Related Questions