2011-10-01 183 views
-1

我想在將二進制數據寫入文件之前暫時緩存二進制數據。這是我的想法。將二進制數據寫入文件

由於我必須在此數據之前插入一個標題,指示在標題後面會有多少數據,所以我需要一種方法在將數據寫入ofstream file之前對其進行高速緩存。我決定創建ostream buffer();,其中我可以轉儲所有這些數據而不寫入文件。

標題寫完後,我只是做file << buffer來轉儲數據。

我仍然有編譯器錯誤掙扎比如這個:

error: no matching function for call to ‘TGA2Converter::writePixel(std::ostream (&)(), uint32_t&)’ 
note: candidate is: void TGA2Converter::writePixel(std::ostream&, uint32_t) 

爲什麼會收到這個消息?而且,或許更重要的是,我是否正在以最有效和最便捷的方式處理問題?


編輯:人一直要求的代碼。我試着將它縮小到這...

// This is a file. I do not want to write the binary 
// data to the file before I can write the header. 
ofstream file("test.txt", ios::binary); 

// This is binary data. Each entry represents a byte. 
// I want to write it to a temporary cache. In my 
// real code, this data has to be gathered before 
// I can write the header because its contents depend 
// on the nature of the data. 
stringstream cache; 
vector<uint32_t> arbitraryBinData; 
arbitraryBinData.resize(3); 
arbitraryBinData[0] = 0x00; 
arbitraryBinData[1] = 0xef; 
arbitraryBinData[2] = 0x08; 

// Write it to temporary cache 
for (unsigned i = 0; i < arbitraryBinData.size(); ++i) 
    cache << arbitraryBinData[i]; 

// Write header 
uint32_t header = 0x80;  // Calculation based on the data! 
file << header; 

// Write data from cache 
file << cache; 

我完全可以預料這個二進制數據寫入文件:

0000000: 8000 ef08 

但我得到這個:

0000000: 3132 3830 7837 6666 6638 6434 3764 3139 
0000010: 38 

爲什麼我沒有得到預期的結果?

+2

發表一些代碼。 –

+0

我已經更新了這個問題。希望能夠清除我想要做的事情。 – Pieter

回答

3

ostream buffer();正在聲明一個函數buffer,該函數不帶任何參數並返回ostream。另外ostream是基類,您應該使用strstream來代替。

+0

Ouch。我注意到'ostream buffer;'後面加了括號,因爲構造函數被保護了......我沒有清楚地思考。我會給strstream一個嘗試,但是我希望它不會破壞文件的二進制編碼。 – Pieter