5

I was looking to use OpenSSL to encrypt text in a file, and will need the text to be in an unsigned char array before I encrypt it. What is the easiest way read text from a file to an unsigned char array?

0

3 Answers 3

9

Your question is tagged both C and C++ (which isn't constructive). I will give an answer for C++.

#include <fstream>
#include <iterator>
#include <vector>

using namespace std;

int main()
{
    ifstream in("filename.txt"); //open file
    in >> noskipws;  //we don't want to skip spaces        
    //initialize a vector with a pair of istream_iterators
    vector<unsigned char> v((istream_iterator<unsigned char>(in)), 
                            (istream_iterator<unsigned char>()));
    ...
}
Sign up to request clarification or add additional context in comments.

7 Comments

@What's evil-looking about it? :)
i'm looking up the documentation for vector(istream_iterator,istream_iterator) now. that's how easy this is
I read your answer to mean something like this: "Your question is tagged both C and C++. (You probably meant C only.) I will give an answer for C++." ;-)
@Amigable: Turns out he meant C++ only as he's edited the question :)
that's why I love stackoverlow. Everytime I can find better way fo doing simple things.
|
3

Read it in whatever data type of your liking. Cast to (unsigned char*) is guaranteed to give you access to the individual bytes.

Edit: This is an answer for C, and not C++. Originally the question was tagged C, too.

4 Comments

Why couldn't you use this answer in C++?
@HighLife, probably you could, but it would be frowned upon. You should make it explicit and use reinterpret_cast<unsigned char*>.
Why would that be frowned upon?
@HighLife: In C++ C cast are generally avoided and replaced by the specialized ones.
1

There must be a ton of examples online of how to do this. The only tricky part is that you will almost certainly need to dynamically allocate memory for the array in order to guarantee that you do not read more input than can fit in the array. Also, you will need to do more research if you need to process large files (say, several GB or larger) that will not fit into a single array of bytes.

Comments

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.