2013-04-14 193 views
4

我正在尝试将数据从二维数组写入二进制文件。我只写入数值大于0的数据。因此,如果数据为0,则不会写入文件。该数据如下:将二维数组写入/读取二进制文件C++

Level  0 1 2 3 4 5 

Row 0  4 3 1 0 2 4 
Row 1  0 2 4 5 0 0 
Row 2  3 2 1 5 2 0 
Row 3  1 3 0 1 2 0 

void { 

    // This is what i have for writing to file. 

    ofstream outBinFile; 
    ifstream inBinFile; 
    int row; 
    int column; 

    outBinFile.open("BINFILE.BIN", ios::out | ios::binary); 

    for (row = 0; row < MAX_ROW; row++){ 

     for (column = 0; column < MAX_LEVEL; column++){ 

      if (Array[row][column] != 0){ 

      outBinFile.write (reinterpret_cast<char*> (&Array[row][column]), sizeof(int) 
      } 
     } 
    } 

    outBinFile.close(); 

    // Reading to file. 

    inBinFile.open("BINFILE.BIN", ios::in | ios::binary); 

    for (row = 0; row < MAX_ROW; row++){ 

     for (column = 0; column < MAX_LEVEL; column++){ 

      if (Array[row][column] != 0){ 

      inBinFile.read (reinterpret_cast<char*> (&Array[row][column]), sizeof(int) 
      } 
     } 
    } 

    inBinFile.close(); 
} 

所有被读取被插入的第一行中的数据,我怎样才能要加载的数据,因为我退出程序?

回答

2

只读数据不等于零时,表示它被第一个零锁定。一旦达到零就停止阅读。

之前“如果命令”读取文件的其他变量然后在if(变量!= 0)数组[行] [列] =变量。

如果你的数组是初始化的数据,也许看看你的阅读设置位置。所以要确定我有零,我应该从另一个位置读下。

+0

谢谢user1678413 – llSpectrell

0

二进制文件需要一个简单的内存转储。我在Mac上,所以我不得不找到一种方法来计算数组的大小,因为sizeof(数组名称)由于某种原因没有返回数组的内存大小(macintosh,netbeans IDE,xCode编译器)。我不得不使用的解决方法是: 写入文件:

fstream fil; 
fil.open("filename.xxx", ios::out | ios::binary); 
fil.write(reinterpret_cast<char *>(&name), (rows*COLS)*sizeof(int)); 
fil.close(); 
//note: since using a 2D array &name can be replaced with just the array name 
//this will write the entire array to the file at once 

读是一样的。由于我使用的Gaddis书籍中的例子在Macintosh上无法正常工作,我必须找到一种不同的方法来实现这一点。只好用下面的代码片段

fstream fil; 
fil.open("filename.xxx", ios::in | ios::binary); 
fil.read(reinterpret_cast<char *>(&name), (rows*COLS)*sizeof(int)); 
fil.close(); 
//note: since using a 2D array &name can be replaced with just the array name 
//this will write the entire array to the file at once 

而不是只让你需要的行*列乘以一个二维数组,然后通过大小相乘来计算整个数组的大小整个数组的大小的数据类型(因为我使用了整型数组,在这种情况下它是int)。