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

4

我正在尝试将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个回答

2

只有在数据不等于零时才进行阅读,这意味着它会在第一个零处停止。一旦达到零,它就停止读取。

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

如果您的数组已初始化了数据,也许可以考虑设置阅读位置。所以,要设置为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),来计算整个数组的大小。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接