Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 237
  • Last Modified:

i need to open a file in hex and save all the data to a txt file

i need to  open a file in hex and save all the data to a txt file
0
ProgramDesign
Asked:
ProgramDesign
  • 2
  • 2
1 Solution
 
chensuCommented:
Read the binary file as a byte stream. Use the sprintf function to convert each byte to a hex string. Write the strings to the text file.

unsigned char byte;
//...

char buf[8];
sprintf(buf, "%02X ", (unsinged int)byte);
0
 
nietodCommented:
That is a very C way to do it.  It works, but I'm surprised chensu wasn't more C++ ish.

for a more C++ approach you can open the file with an fstream object and read bytes.  Then ouput the bytes to another fstream object using the hex  i/o manipulator, like

ifstream In("C:\\SOMEFILE.DAT",ios::in | ios::binary);
ofstream Out("C:\\SOMEFILE.TXT",ios::out);

while (true)
{
   unsigned char Chr;
   In  >> Chr;
   if (In.eof()) // If at the end of the file.
      break; // Stop the loop.
   Out << ios::hex << Chr;
};


Depending on what you want the hex to look like, you might want to add spaces and or/controll the width of the hex numbers pritned.
0
 
chensuCommented:
>but I'm surprised chensu wasn't more C++ ish.

Right. Honestly, I have been doing Windows GUI programming, so I seldom use those stuff, such as cin, cout. The first idea I came up with immediately was to use the Windows API function wsprintf.
0
 
nietodCommented:
You have to write "I will not use C in C++" 100 times..... :-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now