c++visual-c++file-iobinaryfiles

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?


Solution

  • "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 :)