写/读二维数组二进制文件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] = 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在这种情况下)。
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作