Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

need advise in reading binary file

raynaldraynald Posts: 5Member
Hi

i am trying to read a binary file (input.bin)that contains 2 characters
(0x55 0x50).

1 fstream f;
2 char uc;
3 char *uc2;
4 std::ostringstream ost;
5
6 uc2=&uc;
7
8 f.open("c:/input.bin", ios::in|ios::binary);
9 f.read((char *)&uc, 2);
10
11 uc2++;
12
13 ost << uc << *(uc2++);
14 ost.put(0);
15
16 cout << " output "<< ost.str() <<"
";
17 f.close();

Question 1
Why do I need to increment the uc2 twice (at Line 11, Line 13), before I can read in the 2nd character in my binary file correctly?

Question 2
Is there a better way to improve the code?
I am trying to do print out the entire "uc" string in 1 command.

printf(" %s", uc);

(ideal output) UP

If not possible what is another better method than the above code.

Thank you

Comments

  • LundinLundin Posts: 3,711Member
    : Why do I need to increment the uc2 twice (at Line 11, Line 13),
    : before I can read in the 2nd character in my binary file correctly?

    : 2 char uc;

    You allocate 1 byte.

    : 9 f.read((char *)&uc, 2);

    You store 2 bytes at the address of the variable with room for 1 byte. Here, the program would usually crash as it overwrites random memory cells, but I suppose you had luck and those cells contained nothing vital. However, I think this is the cause of your problem. Declare uc as a 2-byte array instead.

    : Question 2
    : Is there a better way to improve the code?

    You should check whether the file was successfully opened or not before attempting to read from it, using the is_open() member function of ofstream.

    : I am trying to do print out the entire "uc" string in 1 command.
    :

    It is not a string, it is two binary values. C strings are always null-terminated, and the binary would have to look like 0x55 0x50 0x00 (3 bytes) in order to work.

    You will either have to change the input file or print the characters one by one.

    : printf(" %s", uc);

    Since you are using C++, avoid printf(). It is much slower and uglier than cout.

Sign In or Register to comment.