0

I'm reading the bytes of a file (an image) to then convert into base64.

The bytes get written into a char vector called buffer, since I haven't found working examples for writing the bytes from the file into a char array

I do the char vector like such:

ifstream infile("image.png", ios_base::binary);

infile.seekg(0, ios_base::end);
size_t length = infile.tellg();
infile.seekg(0, ios_base::beg);

vector<char> buffer;
buffer.reserve(length);
copy(istreambuf_iterator<char>(infile),
    istreambuf_iterator<char>(),
    back_inserter(buffer)); infile.read(&buffer[0], length);

The base64 encoding function is:

int base64_encode(unsigned char *source, size_t sourcelen, char *target, size_t targetlen);

I need to send the base64 encoded text to a website, so that it can be displayed on a page for example.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
mikkel1156
  • 71
  • 3
  • 10
  • 1
    I don't understand why you think you need to "convert" anything. Don't you just need to give a pointer to your vector's buffer to `base64_encode`? Did you consider reading the documentation for `std::vector` to see what it can do? – Lightness Races in Orbit Oct 24 '16 at 01:02
  • 2
    Sorry, what's the problem and what's the question? – Peter Oct 24 '16 at 01:02
  • 1
    How does "convert a char vector to a char array" related to "I need to send the base64 encoded text to a website"? Also, what do you intend to accomplish by that oddly-looking `read()`, after the entire contents of the file get swallowed by `std::copy()`??? – Sam Varshavchik Oct 24 '16 at 01:26
  • Very few programmers always write clean-sheet software. Maintaining a legacy tool built using VC++ 6.0 (yes that still happens) I had the same need. See https://stackoverflow.com/a/4254787/976728 and the comments below it for something helpful. – Firstrock Sep 19 '22 at 16:00

1 Answers1

4

In c++, vectors are dynamically allocated arrays. Whenever you call the .push_back() method, the array is reallocated with the new data appended at the end of the array. If you really need to transfer the data from the vector into a regular array you could use a for loop to assign the data to the array like this:

for (int i = 0; i < vec.size() && i < arrLen; i++) {
    arr[i] = vec[i];
}

Although a much better method considering vectors are just dynamically allocated arrays would be to transfer a raw pointer of the vector's first element to the function.

foo(&vec[0]);

OR

foo(vec.begin());
James Balajan
  • 301
  • 4
  • 13