簡體   English   中英

寫向量 <unsigned char> 在二進制模式下

[英]Write vector<unsigned char> in binary mode

我有以下代碼(C ++)

vector<unsigned char> bytes;
bytes.push_back('e');
bytes.push_back('P');
bytes.push_back('R');
bytes.push_back('f');

...

ofstream file(compiledFile, ios::out | ios::binary);
file.write((const char*) &binary[0], binary.size());
file.close();

但結果是輸出文件我有“ rPRf”而不是字節。

我做錯了什么? 結果,我需要“ 65505266”字節。

謝謝你們。

ePRf為字節。 該文件長4個字符(字節),其中包含您所放置的內容。

“二進制文件”和“文本文件”之間的唯一區別是在Windows上讀取/寫入換行符的方式(以及在很舊的OS上可能還有一些其他特殊字符)。 字符e和數字65之間的唯一區別是您用來讀取文件的程序選擇顯示它的方式。 文本編輯器將顯示e ,十六進制編輯器將顯示65

這是您要做什么?

for( unsigned int i=0; i<bytes.size(); ++i ) {
    file << int(bytes[i]);
}

當我嘗試這個

unsigned char * array = new unsigned char [4];
*(array)='e';
*(array+1)='P';
*(array+2)='R';
*(array+3)='a';

std::ofstream out(fname, std::ofstream::binary);
out.write((char*)array,3);
out.close();

它工作正常,並且在輸出文件中,使用文本編輯器,我只有字節碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM