写/读二维数组二进制文件c++

Writing/Reading 2D array to Binary File C++

本文关键字:二进制文件 c++ 二维数组      更新时间:2023-10-16

我正试图将数据从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();  
}

所有正在读取的数据都被插入到第一行,我如何在退出程序时加载数据?

只在数据不等于零时读取,这意味着它被锁定在第一个零。一旦达到零,它就停止读取。

在"if命令"之前读取文件到其他变量,然后在if (variable != 0) Array[row][column] = variable.

如果你的数组是用data初始化的,也许应该看看你的读取设置位置。所以要设置ok,我有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在这种情况下)。