我需要将一个jpg文件读取为字符串。我想上传这个文件到我们的服务器,但我发现API要求这张图片的数据为字符串。我按照之前我提出的一个问题中所建议的步骤 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;
}
为什么停在60?在60有个奇怪的字符,我应该怎么样将jpg读成字符串?
更新
快了,但是用了建议的方法后,当我将字符串重写到输出文件时,它变形了。发现我还应该通过 ofstream::binary
指定 ofstream 是二进制模式。完成!
顺便问一下,ifstream::binary
和 ios::binary
有什么区别?ofstream::binary
有没有缩写?
ifstream::binary
和ios::binary
以及ofstream::binary
没有区别。binary
在ios_base
类中定义,它是所有 iostream 类的根。ios
是basic_ios<char>
的 typedef,它是在层次结构中介于ios_base
和istream
/ostream
之间的类。我倾向于使用它,因为它很容易输入。您可以同时用于ifstream
和ofstream
的ios::binary
。甚至可以将ifstream::binary
用于ofstream
,反之亦然。 - Benjamin Lindley