保存/加载大量短数组到二进制文件
Save/ load large array of shorts to binary file
我正在尝试写入并随后将非常大的短数据数组读取到文件中。 我正在成功写入,但在读取时,我在文件结束之前很久的读取过程中似乎随机的点在 rdstate 上得到了一个糟糕的位。 这是我当前代码的最小可运行片段:
#include <fstream>
#include <iostream>
int main(int argc, char** argv)
{
short * inData = new short[512 * 512 * 361];
//fill with dummy data
for (int z = 0; z < 361; z++)
{
for (int y = 0; y < 512; y++)
{
for (int x = 0; x < 512; x++)
{
inData[x + y * x + z * y * x] = x + y + z;
}
}
}
//write file
{
std::ofstream outfile("data.bin", std::ios::out, std::ios::binary);
if (outfile.is_open())
{
//header
char buffer[10] = "vol_v1.00";
outfile.write(buffer, 10);
//dimensions
int dims[] = { 512,512,361 };
outfile.write(reinterpret_cast<char*>(dims), std::streamsize(3 * sizeof(int)));
//spacing
double spacing[] = { 0.412,0.412,1 };
outfile.write(reinterpret_cast<char*>(spacing), std::streamsize(3 * sizeof(double)));
//data
outfile.write(reinterpret_cast<const char*>(&inData[0]), sizeof(inData[0]) * dims[0] * dims[1] * dims[2]);
std::cout << "write finished with rdstate: " << outfile.rdstate() << std::endl;
}
}
short * outData = new short[512 * 512 * 361];
//read file
{
std::ifstream infile("data.bin", std::ios::in, std::ios::binary);
if (infile.is_open())
{
// get length of file:
infile.seekg(0, infile.end);
long length = infile.tellg();
infile.seekg(0, infile.beg);
std::cout << "file length: " << length << std::endl;
//header
char buffer[10];
infile.read(reinterpret_cast<char*>(buffer), 10);
std::string header(buffer);
//dimensions
int* dims = new int[3];
infile.read(reinterpret_cast<char*>(dims), std::streamsize(3 * sizeof(int)));
//spacing
double* spacing = new double[3];
infile.read(reinterpret_cast<char*>(spacing), std::streamsize(3 * sizeof(double)));
infile.read(reinterpret_cast<char*>(&outData[0]), std::streamsize(sizeof(outData[0]) * dims[0] * dims[1] * dims[2]));
std::cout << "ending pointer pos: " << infile.tellg() << std::endl;
std::cout << "read finished with rdstate: " << infile.rdstate() << std::endl;
}
}
free(outData);
free(inData);
system("PAUSE");
return 0;
}
我还有其他尝试,我以块为单位阅读,但为了简洁起见,我只是在这里做了一个块,因为问题似乎是一样的。 但是对于块,数据被读取几十万个值,然后以坏位失败。
对 fstream 的两次调用不正确。 如前所述,它仍然在VS2015中编译,但没有正确设置两个标志(写入和二进制(,导致上面看到的流错误。 以下是写入和读取二进制文件的正确调用:
std::ofstream outfile("data.bin", std::ofstream::out | std::ofstream::binary);
std::ifstream infile("data.bin", std::ofstream::in | std::ofstream::binary);
相关文章:
- C++对象数组的文件输出
- 用空格填充 2D 数组(从文件输入)
- 将 matlab 数组(MAT-文件)转换为C++数组
- 我将如何搜索这个包含数组的文件以查找剩余的任何船只?
- 使用数组从文件打印整数
- C 制造功能返回数组交叉文件
- 使用数组增加文件
- 在同一目录下编译两组C 二进制文件
- 从读取到对象指针数组的文件获取段错误
- 如何在python中将包含十六进制值的无符号char*数组写入文件
- 仅显示数组文本文件中的第一个字母
- 二进制 I/O 到具有二维动态数组的文件
- C++ 无法将动态数组写入文件
- 如何将动态分配的多维结构数组写入文件
- 如何将二进制数组写入文件
- C++使用填充将字符数组写入文件
- 将数组写入文件代码不起作用(C++)
- C++ 将"Already Formatted"数组从文件读取到 Int 数组?
- 如何将字符串行作为cl_uint数组和文件详细信息传递给GPGPU
- 写/读二维数组二进制文件c++