Output a binary file in hexadecimal : binary file « File Stream « C++ Tutorial






#include <iostream>
#include <fstream>
#include <ctype.h>
#include <iomanip>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[]){

   ifstream in("text.txt", ios::in | ios::binary);
   if(!in){
      cout << "Cannot open input file." << endl;
      exit (1);
   }

   int i, j;
   int count = 0;
   char c[16];

   cout.setf(ios::uppercase);
   while(!in.eof()){
      for(i=0; i<16 && !in.eof(); i++)
         in.get(c[i]);
      if(i<16)
         i--;
      for(j=0; j < i; j++)
         cout << setw(3) << hex << (int) c[j];
      for(; j < 16; j++)
         cout << "  ";
   
      for(j=0; j < i; j++)
         if(isprint(c[j]))
            cout << c[j];
         else
            cout << ".";
      cout << endl;
      count ++;
      if(count==16){
         count = 0;
         cout << "Press ENTER to continue: ";
         cin.get();
         cout << endl;
       }
    }
    in.close();
}








12.3.binary file
12.3.1.Open a binary file
12.3.2.Reading binary file
12.3.3.Open a binary file and read
12.3.4.Output a binary file in hexadecimal
12.3.5.Write Unformatted Binary Data to a File
12.3.6.Use read() to input blocks of binary data.
12.3.7.Use write() to output a block of binary data.
12.3.8.Creating a randomly accessed file
12.3.9.Append to a binary file
12.3.10.Unformatted and Binary I/O