【发布时间】:2013-07-11 03:56:20
【问题描述】:
我需要将 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之间的类。我倾向于使用它,因为它很容易输入。您可以将ios::binary用于ifstream和ofstream。您甚至可以将ifstream::binary用于ofstream,反之亦然。
标签: c++ file-upload file-io