sworwitz
sworwitz

Reputation: 19

Open any file as a binary file

I was wondering how could I open any file (jpg, txt, zip, cpp, ...) as a binary file. I want to see the bytes before they could be formatted by the program that normally would interpret that file format. It's possible? How could I do it in c++? Thanks.

Upvotes: 0

Views: 2606

Answers (2)

max66
max66

Reputation: 66230

You can use the old C interface (fopen(), etc.) but the C++ way is based on file stream: fstream, ifstream, ofstream, wfstream, etc.

To open in binary mode (and not text mode) you have to use the flag std::ios::binary.

By example, you can read a file (one char at a time) in the following way

#include <fstream>
#include <iostream>

int main()
 {
   char ch;

   std::ifstream fl("file.log", std::ios::binary);

   while ( fl.read(&ch, sizeof(ch)) )
      std::cout << "-- [" << int(ch) << "]" << std::endl;

   return 0;
 }

p.s.: sorry for my bad English

Upvotes: 0

Omar
Omar

Reputation: 973

You can use POSIX (C way but works in C++) functions to do so :

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int fd = open("file.bin", O_RDONLY); //Opens the file
if(fd<0){
    perror("Error opening the file");
    exit(1);
}
char buf[1024];
int i;
ssize_t rd;
for(;;){
   rd = read(fd, buf, 1024);
   if(rd==-1) //Handle error as we did for open
   if(rd==0) break;
   for(i = 0; i < rd; i++)
     printf("%x ", buf[i]); //This will print the hex value of the byte
   printf("\n");
}
close(fd);

Upvotes: 1

Related Questions