将二维数组写入/读取到二进制文件C ++

时间:2013-04-14 18:23:31

标签: c++ multidimensional-array binaryfiles binary-data

我正在尝试将数据从2D数组写入二进制文件。我只编写值大于0的数据。因此,如果数据为0,则不会将其写入文件。数据如下:

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 个答案:

答案 0 :(得分:2)

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

在“if命令”之前将文件读取到其他一些变量然后在if(变量!= 0)数组[row] [column] = variable。

如果使用数据初始化数组,可能需要查看设置的读数位置。所以设置好我没有,我应该从另一个位置读下一个。

答案 1 :(得分: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

不是只获取整个数组的大小,而是需要通过将2d数组的行*列相乘来计算整个数组的大小,然后将其乘以数据类型的大小(因为我使用了整数数组)在这种情况下是int。)

相关问题