我需要將jpg文件讀取到字符串。我想上傳這個文件到我們的服務器,我只是發現API需要一個字符串作爲這張圖的數據。我在前一個問題中遵循了這些建議,我詢問了Upload pics to a server using c++。使用C++讀取二進制文件(jpg)爲字符串
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?
UPDATE
快到了,但使用建議的方法,當我重寫字符串輸出文件後,它扭曲了。找出我應該指定的流是由二進制模式ofstream::binary
。完成!
順便說一句ifstream::binary
& ios::binary
有什麼區別,有沒有ofstream::binary
的縮寫?
'ifstream :: binary'和'ios :: binary',甚至'ofstream :: binary'之間沒有區別。 'binary'在'ios_base'類中定義,它是所有iostream類的根。 'ios'是'basic_ios'的一個typedef,它是一個落在層次結構中'ios_base'和'istream' /'ostream'之間的類。我傾向於使用它,因爲它很容易輸入。你可以在'ifstream'和'ofstream'中使用'ios :: binary'。你甚至可以用'ifstream :: binary'作爲'ofstream',反之亦然。 –