如何保存和读取二进制数据?
How to Save and Read Binary Data?
>我再次需要您的帮助来保存和读取二进制数据。我有一个从硬件读取 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;
}
您可以在计算机上运行此演示。如果此演示有效,则可能是您在代码中犯了一些错误。请提供一个完整且可核实的示例。
相关文章:
- 正在读取二进制文件(is_open)
- 如何从dicom文件中读取二进制数据
- C++用于从流中读取二进制值的任何标准库
- readsome() 适合在 Windows 上读取二进制数据吗?
- 读取二进制文件并解释为整数
- 读取二进制文件直到结束 c++
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?
- 读取二进制文件的惯用C++17标准方法是什么
- 从末尾读取二进制文件
- C++逐个字符读取二进制文件字符
- 读取二进制文件大小的短自上周以来停止工作
- 读取二进制文件时出现问题
- 读取二进制文件时如何输出?
- C++:如何在线程中读取二进制文件并将其写入另一个线程?
- 在C 中读取二进制文件会返回意外值
- 尝试读取二进制文件会清除文件本身
- C 读取二进制文件
- 通过C 读取二进制文件的问题
- 用ifstream read()读取二进制的结构
- ifstream读取二进制文件在发行模式下工作,但在调试模式下不使用