2016-04-11 47 views
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 *。所以問題如下:

  1. 我是否正確寫入文件?如果不是,那麼正確的方法是什麼。
  2. 如何將一個char向量轉換爲一個unsigned char向量?

謝謝。

回答

2

您在這裏有一個範圍問題。您在哪裏說BYTE *rgbPlaintext = (BYTE*)&contents[0] ;您正在聲明一個名爲rgbPlaintext的變量,該變量位於您的if聲明後面的大括號內。從編譯器的角度來看,這與您在程序開始時聲明的rgbPlaintext不同。只要您爲第二個rgbPlaintext分配一個值,就會遇到大括號,這會導致該值被丟棄。

頂部的說法應該是

BYTE *rgbPlaintext; 

和右大括號前的最後一條語句應該是

rgbPlaintext = (BYTE*)&contents[0] ; 

沒有BYTE *部分。

這樣,您仍然可以在if聲明之後的代碼中訪問rgbPlaintext

+0

我刪除了BYTE部分,現在它給出了一個錯誤:表達式必須是可修改的值 – ITWorker

+0

注意星號在哪裏很重要。你首先聲明應該是'BYTE * rgbPlaintext;'而不是'BYTE rgbPlaintext [] = {0x00};'。那麼'if'語句底部的引用應該只是一個引用,而不是一個定義,例如'rgbPlaintext =(BYTE *)&contents [0];'而不是'BYTE * rgbPlaintext =(BYTE *)&contents [0];'。 – Logicrat