我使用「writeFileBytes」下面的函數將std::vector<unsigned char>
的內容寫入文件。我想使用「unsigned char」類型來保存文件(注意對「char」進行強制轉換)。這個問題的原因是因爲「無符號字符」與任何字節(例如「00000000」位)兼容。當我們使用「char」時,我們在處理某些「無效」字符時遇到了一些問題。C++ - 將「std :: vector <unsigned char>」的內容保存到文件中
有關「00000000」位(1字節)問題的更多信息,請參閱此主題What is the most suitable type of vector to keep the bytes of a file?。
void writeFileBytes(const char* filename, std::vector<unsigned char>& fileBytes){
std::ofstream file(filename, std::ios::out|std::ios::binary);
file.write(fileBytes.size() ? (char*)&fileBytes[0] : 0,
std::streamsize(fileBytes.size()));
}
writeFileBytes("xz.bin", fileBytesOutput);
是否有使用類型爲「無符號的字符」本身寫入到文件的方法嗎?
這個問題真的有道理嗎?
更新我:
是否有使用類型爲「無符號的字符」本身寫入到文件的方法嗎? - >是的!
遵循krzaq的指導方針!
void writeFileBytes(const char* filename, std::vector<unsigned char>& fileBytes){
std::ofstream file(filename, std::ios::out|std::ios::binary);
std::copy(fileBytes.cbegin(), fileBytes.cend(),
std::ostream_iterator<unsigned char>(file));
}
UPDATE II:
這種擔心真的有意義嗎? - >在某些方面,是的!
正如我在下面評論...
」 ......‘無符號的字符’似乎有一個‘兼容性更高水平’(包括‘00000000’位)。當我們嘗試這些8位轉換('00000000'bits)'char'我們沒有任何價值,不像'unsigned char'。'unsigned char'我們有一個無效/無法識別的'char'值,但是我們有......「
看到這個話題What is the most suitable type of vector to keep the bytes of a file?瞭解更多信息!
對於社區而言,如果消極情緒伴隨着解釋或理由,那麼對於社區來說這是非常好的事情,並且會豐富它(像我一樣)。通過這種方式我們可以一起改善事物!如果有什麼問題,我可以修復或刪除此線程。我相信我們是合理的人。 –
「00000000」位(1字節)不能被類型「char」識別。當我們試圖將這8位轉換爲「char」時,我們沒有像「unsigned char」那樣的價值。用「無符號字符」我們有一個無效/無法識別的「字符」值,但我們有。我建議看看http://stackoverflow.com/questions/40052857/c-save-the-contents-of-a-stdvectorunsigned-char-to-a-file/40052889#40052889中的所有討論。謝謝! –