2010-12-04 45 views
1

我有一些嚴重的奇怪的麻煩寫入多個數據數組到一個文件。基本上,我想要將所有數組大小存儲在文件頂部,然後是數組數據。這樣我就可以讀取大小,並使用它來構造數組來保存導入數據,並且我將確切知道每個數組開始和結束的位置。使用ofstream將多個數組指針寫入文件?

問題出在這裏:我寫了數據,但導入數據不同。請看看我的小測試代碼。底部有關於價值的評論。

非常感謝各位程序員! :)

#include <iostream> 
#include <fstream> 

int main() 
{ 
    int  jcount = 100, // First item in file 
      kcount = 200, 
      in_jcount, // Third item in file. jcount is used to find where this ends. 
      in_kcount; 

    float *j = new float[jcount], 
      *k = new float[kcount], 
      *in_j, 
      *in_k; 

    for(int i = 0; i < jcount; ++i) // Write bologna data... 
     j[i] = (float)i; 
    for(int i = 0; i < kcount; ++i) 
     k[i] = (float)i; 

    std::ofstream outfile("test.dat"); 

    outfile.write((char*)&jcount, sizeof(int)); // Good 
    outfile.tellp(); 

    outfile.write((char*)&kcount, sizeof(int)); // Good 
    outfile.tellp(); 

    outfile.write((char*)j, sizeof(float) * jcount); // I don't know if this works! 
    outfile.tellp(); 

    outfile.write((char*)k, sizeof(float) * kcount); // I don't know if this works! 
    outfile.tellp(); 

    outfile.close(); 


    std::ifstream in("test.dat"); 

    in.read((char*)&in_jcount, sizeof(int)); // == jcount == 100, good. 
    in.read((char*)&in_kcount, sizeof(int)); // == kcount == 200, good. 

    in_j = new float[in_jcount], 
    in_k = new float[in_kcount]; // Allocate arrays the exact size of what it should be 

    in.read((char*)in_j, sizeof(float) * in_jcount); // This is where it goes bad! 
    in.read((char*)in_k, sizeof(float) * in_kcount); 

    float jtest_min = j[0], // 0.0 
      jtest_max = j[jcount - 1], // this is 99. 

      ktest_min = k[0], // 0.0 
      ktest_max = k[kcount - 1], // this is 200. Why? It should be 199! 

      in_jtest_min = in_j[0], // 0.0 
      in_jtest_max = in_j[in_jcount - 1], // 99 

      in_ktest_min = in_k[0], // 0.0 
      in_ktest_max = in_k[in_kcount - 1]; // MIN_FLOAT, should be 199. What is going on here? 

    in.close(); 

    delete k; 
    delete j; 
    delete in_j; 
    delete in_k; 
} 
+0

這不回答你的問題,但我只是想指出,如果你用`new []`初始化一個對象,你應該用`delete []`將其銷燬。另外,只是一個簡單的問題:你看看`test.dat`來看看它是否正確地寫出了所有的數組? – 2010-12-04 05:48:58

回答

1

沒有什麼明顯的錯誤與此代碼(事實上,我不明白您遇到的錯誤,當我嘗試運行它)是,除了一個事實,你是不是檢查錯誤打開輸入/輸出文件。

例如,如果您沒有寫入「test.dat」的權限,則打開將默默失敗,並且您將回讀以前在文件中發生的任何事情。

+0

你的意思是它在你的電腦上完美運行?你會得到相同的數據陣列,因爲它應該出來? – 2010-12-04 03:47:39

1

我已經得到了同樣的錯誤,我用的二進制文件修復:

ofstream outfile; 
outfile.open ("test.dat", ios::out | ios::binary); 

ifstream in; 
in.open ("test.dat", ios::in | ios::binary);