繁体   English   中英

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

[英]Writing/Reading 2D array to Binary File C++

我正在尝试将数据从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] =变量。

如果您的Array已使用数据初始化,则可以查看读数的设置位置。 因此要设置好我为零,接下来我应该从另一个位置读取。

二进制文件进行简单的内存转储。 我在Mac上,所以我不得不找到一种计算数组大小的方法,因为sizeof(array name)由于某种原因(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 in这个案例)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM