Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text from file to unsigned char array

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?

like image 657
HighLife Avatar asked Jul 26 '11 13:07

HighLife


3 Answers

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>()));
    ...
}
like image 129
Armen Tsirunyan Avatar answered Oct 21 '22 19:10

Armen Tsirunyan


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.

like image 3
Jens Gustedt Avatar answered Oct 21 '22 19:10

Jens Gustedt


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.

like image 1
Justin Ethier Avatar answered Oct 21 '22 21:10

Justin Ethier