使用c ++读取二进制文件(jpg)到字符串 [英] Read a binary file (jpg) to a string using c++
问题描述
我需要读一个jpg文件到一个字符串。我想把这个文件上传到我们的服务器,我只是发现,API需要一个字符串作为这个pic的数据。我按照先前问题中的建议上传图片到服务器使用c ++ 。
int main(){
ifstream fin(cloud.jpg);
ofstream fout(test.jpg); //为测试目的,看看字符串是否是正确的副本
ostringstream ostrm;
unsigned char tmp;
int count = 0;
while(fin>> tmp){
++ count; //用于测试目的
ostrm< tmp;
}
string data(ostrm.str());
cout<< count<< endl; // ouput 60!肯定不是正确的大小
fout< string; //只有60个字节
return 0;
}
为什么在60时停止?这是一个奇怪的字符在60,我应该怎么做把jpg读到一个字符串?
UPDATE
几乎存在,但使用建议的方法后,将字符串重写到输出文件,它扭曲。发现我还应该通过 ofstream :: binary
指定ofstream是二进制模式。完成!
顺便说一句, ifstream :: binary
ios :: binary
,是否有任何缩写 ofstream :: binary
?
以二进制模式打开文件,否则它会有一些有趣的行为,它会以不当的方式处理某些非文本字符,至少在Windows上。 p>
ifstream fin(cloud.jpg,ios :: binary);
此外,而不是while循环,你可以一次读取整个文件:
ostrm<< fin.rdbuf();
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
?
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();
这篇关于使用c ++读取二进制文件(jpg)到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!