2012-11-13 38 views
5

我正在嘗試將雙精度矢量寫入二進制文件。 做完這些之後,我想閱讀它。這似乎並不奏效。 下面是代碼:將矢量<double>寫入二進制文件並再次讀取

ofstream bestand; 
vector<double> v (32); 
const char* pointer = reinterpret_cast<const char*>(&v[0]); 
size_t bytes = v.size() * sizeof(v[0]); 
bestand.open("test",ios::out | ios::binary); 
for(int i = 0; i < 32; i++) 
{ 
    v[i] = i; 
    cout << i; 
    } 
bestand.write(pointer, v.size()); 
bestand.close(); 
ifstream inlezen; 
vector<double> v2 (32); 
inlezen.open("test", ios::in | ios::binary); 
char byte[8]; 
bytes = v2.size() * sizeof(v2[0]); 
inlezen.read(reinterpret_cast<char*>(&v2[0]), bytes); 
for(int i =0; i < 32; i++){ 

cout << endl << v2[i] << endl; 
} 

此輸出 「0 1 2 3 0 0 0 ......」,因此它似乎它正確地讀取第一個4號。

+3

'write()'大小參數不正確。它應該是'v.size()* sizeof(double)'。 – hmjd

+0

@ K-ballo'skipws'不適用於無格式輸入。 –

回答

7

.write()需要的字節數,寫不是項目數量:

bestand.write(pointer, v.size()); 

既然你已經計算出正確的值,使用它:

bestand.write(pointer, bytes); 
+0

hmjd擊敗了我30秒。 –

+0

@MagnusHoff當然。固定。 –

+0

這個作品謝謝你!假設我有一個for循環,將每個迭代的新矢量寫入同一個文件。我必須改變閱讀方式?此外,但在循環? – pivu0

相關問題