Read a binary file (jpg) to a string using c++ -
i need read jpg file string. want upload file our server, find out api requires string data of pic. followed suggestions in former question i've asked upload pics server using c++ .
int main() { ifstream fin("cloud.jpg"); ofstream fout("test.jpg");//for testing purpose, see if string 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! not right size fout << string;//only 60 bytes return 0; }
why stops @ 60? it's strange character @ 60, , should read jpg string?
update
almost there, after using suggested method, when rewrite string output file, distorted. find out should specify ofstream in binary mode ofstream::binary
. done!
by way what's difference between ifstream::binary
& ios::binary
, there abbreviation ofstream::binary
?
open file in binary mode, otherwise have funny behavior, , handle non-text characters in inappropriate ways, @ least on windows.
ifstream fin("cloud.jpg", ios::binary);
also, instead of while loop, can read whole file in 1 shot:
ostrm << fin.rdbuf();
Comments
Post a Comment