a simple C++ question (about binary file input)

N

news.hku.hk

i have a binary file "myfile.bin", its output of "od -t x1 myfile.bin" is:

0000000 7f 45 4c 46 01 02 01

and longer. i want the output to screen be:

7f 45 4c 46 01 02 01

i try to write the program like that:

char ch2;
ifstream ifs ("myfile.bin", ios:binary|ios::in);
while (ifs.get(ch2)) { *****
cout.put(ch2); *****
}
ifs.close(); return 0;

i think the two lines with ***** are problematic, could anyone gives me a
helping hand? thanks for reading this post.
 
V

Victor Bazarov

news.hku.hk said:
i have a binary file "myfile.bin", its output of "od -t x1 myfile.bin" is:

0000000 7f 45 4c 46 01 02 01

and longer. i want the output to screen be:

7f 45 4c 46 01 02 01

i try to write the program like that:

char ch2;
ifstream ifs ("myfile.bin", ios:binary|ios::in);
while (ifs.get(ch2)) { *****
cout.put(ch2); *****

You probably want to do

cout << int(ch2) << ' ';
}
ifs.close(); return 0;

i think the two lines with ***** are problematic, could anyone gives me a
helping hand? thanks for reading this post.

Victor
 
N

Nick Hounsome

news.hku.hk said:
i have a binary file "myfile.bin", its output of "od -t x1 myfile.bin" is:

0000000 7f 45 4c 46 01 02 01

and longer. i want the output to screen be:

7f 45 4c 46 01 02 01

These are hex integers not chars.
cat shows chars
od shows the hexadecimal integer values of those chars (using 2 chars per
char :)
i try to write the program like that:
#include said:
char ch2;
ifstream ifs ("myfile.bin", ios:binary|ios::in);

cout << std::hex << std::setfill('0'); // use hex for
ints and padd with leading 0
while (ifs.get(ch2)) { *****

// each char is 2 hex digits and width isn't sticky so it
must be done for each
cout << ' ' << std::setw(2) << int(ch2);

cout << dec << setfill(' '); // set back to default - this isn't
ideal but proper saving and restoring of state is messy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top