1
我有一個向量定義如下:關於無符號的字符,字符,字節和文件寫入問題
std::vector<char> contents;
我的目標是文件讀入字節數組,這是無符號的字符的類型定義。我嘗試如下:
BYTE rgbPlaintext[] = {0x00};
std::ifstream in;
std::vector<char> contents;
in.open("test.dat", std::ios::in | std::ios::binary);
if (in.is_open())
{
// get the starting position
std::streampos start = in.tellg();
// go to the end
in.seekg(0, std::ios::end);
// get the ending position
std::streampos end = in.tellg();
// go back to the start
in.seekg(0, std::ios::beg);
// create a vector to hold the data that
// is resized to the total size of the file
contents.resize(static_cast<size_t>(end - start));
// read it in
in.read(&contents[0], contents.size());
BYTE *rgbPlaintext = (BYTE*)&contents[0] ;
}
但是,當我寫rgbPlainText到一個文件,使用以下:
std::ofstream f("testOut.dat",std::ios::out | std::ios::binary);
for(std::vector<char>::const_iterator i = contents.begin(); i != contents.end(); ++i)
{
f << *rgbPlaintext;
}
這只是一個空行。 test.dat文件包含可讀的文本。我怎樣才能讓它正常工作?當我將矢量更改爲無符號字符而不是現在定義的字符時,我在「讀入」步驟中遇到了一個錯誤,表示預期的參數類型是char *,而輸入的參數是unsigned char *。所以問題如下:
- 我是否正確寫入文件?如果不是,那麼正確的方法是什麼。
- 如何將一個char向量轉換爲一個unsigned char向量?
謝謝。
我刪除了BYTE部分,現在它給出了一個錯誤:表達式必須是可修改的值 – ITWorker
注意星號在哪裏很重要。你首先聲明應該是'BYTE * rgbPlaintext;'而不是'BYTE rgbPlaintext [] = {0x00};'。那麼'if'語句底部的引用應該只是一個引用,而不是一個定義,例如'rgbPlaintext =(BYTE *)&contents [0];'而不是'BYTE * rgbPlaintext =(BYTE *)&contents [0];'。 – Logicrat