2010-12-04 44 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);