Read a binary file (jpg) to a string using c++

c++, file-io, file-upload

Solution

Open the file in binary mode, otherwise it will have funny behavior, and it will handle certain non-text characters in inappropriate ways, at least on Windows.

ifstream fin("cloud.jpg", ios::binary);

Also, instead of a while loop, you can just read the whole file in one shot:

ostrm << fin.rdbuf();

Problem

I need to read a jpg file to a string. I want to upload this file to our server, I just find out that the API requires a string as the data of this pic. I followed the suggestions in a former question I've asked Upload pics to a server using c++ . ``` int main() { ifstream fin("cloud.jpg"); ofstream fout("test.jpg");//for testing purpose, to see if the string is a right copy ostringstream ostrm; unsigned char tmp; int count = 0; while ( fin >> tmp ) { ++count;//for testing purpose ostrm << tmp; } string data( ostrm.str() ); cout << count << endl;//ouput 60! Definitely not the right size fout << string;//only 60 bytes return 0; } ``` Why it stops at 60? It's a strange character at 60, and what should I do to read the jpg to a string? UPDATE Almost there, but after using the suggested method, when I rewrite the string to the output file, it distorted. Find out that I should also specify that the ofstream is in binary mode by `ofstream::binary`. Done! By the way what's the difference between `ifstream::binary` & `ios::binary`, is there any abbreviation for `ofstream::binary`?

Original source

Related problems