2

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

But how can I read the binary file?

LihO
  • 41,190
  • 11
  • 99
  • 167
  • Welcome to SO. Note that you should provide more information. Also it doesn't show any effort of yours. What have you tried? Read [FAQ](http://stackoverflow.com/faq) :) – LihO Mar 12 '13 at 16:26

1 Answers1

17

"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::streampos fileSize;
    std::ifstream file(filename, std::ios::binary);

    // get its size:
    file.seekg(0, std::ios::end);
    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 :)

starriet
  • 2,565
  • 22
  • 23
LihO
  • 41,190
  • 11
  • 99
  • 167
  • It'd be cool if the OP inherited `std::fstream` and created a `fencryptstream' that did the encoding decoding transparently inside the class. – Matt Clarkson Mar 12 '13 at 17:22
  • LihO "can this work with large file that size up to 250MB please help me" – Mohmmad AL-helawe Mar 13 '13 at 14:34
  • @MohmmadAL-helawe: If you are experiencing some problems with large files, then post it as a new question :) Just make sure that you describe your problem properly, so that people can help you :) – LihO Mar 13 '13 at 14:41
  • for future ref) see [this](https://stackoverflow.com/q/15138353/10027592) question by LihO, for more discussion. – starriet Aug 25 '23 at 14:54