I have been search on the internet for a way to read binary files in c++, and I have found two snippets that kind of works:
No.1:
#include <iostream>
#include <fstream>
int main(int argc, const char *argv[])
{
if (argc < 2) {
::std::cerr << "Usage: " << argv[0] << "<filename>\n";
return 1;
}
::std::ifstream in(argv[1], ::std::ios::binary);
while (in) {
char c;
in.get(c);
if (in) {
// ::std::cout << "Read a " << int(c) << "\n";
printf("%X ", c);
}
}
return 0;
}
Result:
6C 1B 1 FFFFFFDC F FFFFFFE7 F 6B 1
No.2:
#include <stdio.h>
#include <iostream>
using namespace std;
// An unsigned char can store 1 Bytes (8bits) of data (0-255)
typedef unsigned char BYTE;
// Get the size of a file
long getFileSize(FILE *file)
{
long lCurPos, lEndPos;
lCurPos = ftell(file);
fseek(file, 0, 2);
lEndPos = ftell(file);
fseek(file, lCurPos, 0);
return lEndPos;
}
int main()
{
const char *filePath = "/tmp/test.bed";
BYTE *fileBuf; // Pointer to our buffered data
FILE *file = NULL; // File pointer
// Open the file in binary mode using the "rb" format string
// This also checks if the file exists and/or can be opened for reading correctly
if ((file = fopen(filePath, "rb")) == NULL)
cout << "Could not open specified file" << endl;
else
cout << "File opened successfully" << endl;
// Get the size of the file in bytes
long fileSize = getFileSize(file);
// Allocate space in the buffer for the whole file
fileBuf = new BYTE[fileSize];
// Read the file in to the buffer
fread(fileBuf, fileSize, 1, file);
// Now that we have the entire file buffered, we can take a look at some binary infomation
// Lets take a look in hexadecimal
for (int i = 0; i < 100; i++)
printf("%X ", fileBuf[i]);
cin.get();
delete[]fileBuf;
fclose(file); // Almost forgot this
return 0;
}
Result:
6C 1B 1 DC F E7 F 6B 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A1 D 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
The result of xxd /tmp/test.bed
:
0000000: 6c1b 01dc 0fe7 0f6b 01 l......k.
The result of ls -l /tmp/test.bed
-rw-rw-r-- 1 user user 9 Nov 3 16:37 test.bed
The second method is giving the right hex codes in the beginning but seems got the file size wrong, the first method is messing up the bytes.
These methods look very different, perhaps there are many ways to do the same thing in c++? Is there an idiom that pros adopt?