保存/加载大量短数组到二进制文件

Save/ load large array of shorts to binary file

本文关键字:数组 二进制文件 加载 保存      更新时间:2023-10-16

我正在尝试写入并随后将非常大的短数据数组读取到文件中。 我正在成功写入,但在读取时,我在文件结束之前很久的读取过程中似乎随机的点在 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);