如何保存和读取二进制数据?

How to Save and Read Binary Data?

本文关键字:读取 二进制 数据 何保存 保存      更新时间:2023-10-16

>我再次需要您的帮助来保存和读取二进制数据。我有一个从硬件读取 10 次的vector<<complex> > xy(256)

vector<<complex> > xy(256);
ofstream outfile2 (outfilename2.c_str() , ofstream::binary);
....
....
for(unsigned t = 0; t < 10; t++)
{
....
....
for(unsigned i = 0; i < 256; i++)
{
xy[i] = f[i] * conj(g[i]);
}
for(unsigned i = 0; i < 256; i++)
{
outfile2 << boost::format("%20.8e") % xy[i]<< endl;  // write in text
}
}  // the text data will be 2560 lines of complex data, for example:
// (6.69635350e+06,7.34146150e+06)

现在,我正在尝试使用以下命令保存到二进制文件中:

for(unsigned i = 0; i < 256; i++)
{
outfile2.write((const char*)& xy[i], 1 * sizeof(complex<short>));
outfile2.flush();
}

虽然,它仍然给了我一个数据,但是当我与原始文本数据进行比较时,它们是不同的。我不明白为什么?

我想读取带有浮点数据的复杂 16。

希望你们能帮上忙。

谢谢。

我写了一个演示,可以在我的电脑上工作。

#include <cassert>
#include <complex>
#include <fstream>
#include <iostream>
#include <type_traits>
#include <vector>
int main() {
assert( std::is_trivially_copy_assignable<std::complex<short> >::value );
std::vector<std::complex<short> > vtr(256);
for (int i=0; i<256; ++i)
vtr[i] = std::complex<short>(i*2,i*2+1);
{
std::ofstream output("data.bin", std::ofstream::binary);
for (int i=0; i<256; ++i)
output.write((char *)&vtr[i],sizeof(vtr[i]));
}
vtr.clear();
std::cout << vtr.size() << std::endl;
vtr.resize(256);
{
std::ifstream input("data.bin", std::ifstream::binary);
for (int i=0; i<256; ++i)
input.read((char *)&vtr[i],sizeof(vtr[i]));
}
for (size_t i=0; i<vtr.size(); ++i)
std::cout << vtr[i] << " ";
std::cout << std::endl;
return 0;
}

您可以在计算机上运行此演示。如果此演示有效,则可能是您在代码中犯了一些错误。请提供一个完整且可核实的示例。