[英]How can I read and write unsigned chars to files with fstream in c++?
到目前為止,我有代碼從ifstream讀取unsigned char:
ifstream in;
unsigned char temp;
in.open ("RANDOMFILE", ios::in | ios::binary);
in.read (&temp, 1);
in.close ();
它是否正確? 我還嘗試將一個unsigned char寫入ofstream:
ofstream out;
unsigned char temp;
out.open ("RANDOMFILE", ios::out | ios::binary);
out.write (&static_cast<char>(temp), 1);
out.close ();
但是我寫錯了以下錯誤:
error C2102: '&' requires l-value
這個錯誤用於閱讀:
error C2664: 'std::basic_istream<_Elem,_Traits>::read' : cannot convert parameter 1 from 'unsigned char *' to 'char *'
如果有人能告訴我我的代碼有什么問題,或者我如何從fstream讀取和寫入未簽名的字符,我們將不勝感激。
寫入錯誤告訴您正在獲取static_cast
創建的臨時地址。
代替:
// Make a new char with the same value as temp
out.write (&static_cast<char>(temp), 1);
在temp中使用相同的數據:
// Use temp directly, interpreting it as a char
out.write (reinterpret_cast<char*>(&temp), 1);
如果您告訴編譯器將數據解釋為char ,則讀取錯誤也將得到修復:
in.read (reinterpret_cast<char*>(&temp), 1);
read
函數總是將字節作為參數,為方便起見,表示為char
值。 您可以根據需要將指針轉換為這些字節,所以
in.read (reinterpret_cast<char*>(&temp), 1);
將讀取單個字節就好了。 請記住,內存是內存是內存,而C ++的類型只是對內存的解釋。 當您將原始字節讀入原始內存時(與read
),您應首先讀取然后轉換為適當的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.