4

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

But how can I read the binary file?

1
  • 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 :) Commented Mar 12, 2013 at 16:26

1 Answer 1

18

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

Sign up to request clarification or add additional context in comments.

5 Comments

It'd be cool if the OP inherited std::fstream and created a `fencryptstream' that did the encoding decoding transparently inside the class.
LihO "can this work with large file that size up to 250MB please help me"
@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 :)
for future ref) see this question by LihO, for more discussion.
Why, when compiling this code in Qt Creator, I get the errors "undefined reference to WinMain16" and "Id returned 1 exit status"? I'm a newbie.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.