我正在編寫一些串行端口代碼,需要將文件的內容(二進制)讀取到變量中。 從「二進制文件」的例子在http://www.cplusplus.com/doc/tutorial/files/, 起始I嘗試打開.jpg文件:用於讀取二進制文件的變量的問題
#include <iostream>
#include <fstream>
using namespace std;
ifstream::pos_type size;
char * memblock;
int main() {
ifstream file ("example.jpg", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << memblock << endl;
delete[] memblock;
}
else cout << "Unable to open file";
return 0;
}
然而,僅前4個字符(32位)被印刷在控制檯中。
什麼特別奇怪的是,雖然使用的ostream :: write()方法與假想故障變量「memblock」完美的作品:
ofstream fileOut ("writtenFile.jpg",ios::out|ios::binary);
fileOut.write(memblock,size);
fileOut.close();
即它會創建一個新的.jpg文件。
所以我的問題是爲什麼memblock變量似乎只包含前4個字符。