我正在尝试写入文件,然后将大量的短数据读取到文件中。我的写入成功,但是在读取时,在文件结束前很久的读取过程中,在看似随机的点上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;
}
我还有其他尝试读取大块的尝试,但是为了简洁起见,这里只做了单个大块,因为问题似乎相同。但是对于大块数据,将读取数十万个值的数据,然后以坏位失败。
答案 0 :(得分: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);