Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the binary file in C++

I want to write a program that opens the binary file and encrypts it using DES.

But how can I read the binary file?

like image 904
Mohmmad AL-helawe Avatar asked Oct 31 '25 11:10

Mohmmad AL-helawe


1 Answers

"how can I read the binary file?"

If you want to read the binary file and then process its data (encrypt it, compress, etc.), then it seems reasonable to load it into the memory in a form that will be easy to work with. I recommend you to use std::vector<BYTE> where BYTE is an unsigned char:

#include <fstream>
#include <vector>
typedef unsigned char BYTE;

std::vector<BYTE> readFile(const char* filename)
{
    // open the file:
    std::ifstream file(filename, std::ios::binary);

    // get its size:
    file.seekg(0, std::ios::end);
    std::streampos fileSize = file.tellg();
    file.seekg(0, std::ios::beg);

    // read the data:
    std::vector<BYTE> fileData(fileSize);
    file.read((char*) &fileData[0], fileSize);
    return fileData;
}

with this function you can easily load your file into the vector like this:

std::vector<BYTE> fileData = readFile("myfile.bin");

Hope this helps :)

like image 190
LihO Avatar answered Nov 03 '25 00:11

LihO