c++ - 只读取二进制文件的第一行
问题描述
函数应该创建复杂(我的结构)向量,而不是将其保存到二进制文件中,然后从二进制文件中读取它。问题是它只在第一行读得很好。
结构很好。除了阅读,一切都很好。这些是读取和写入函数:
void saveVectorBin(vector<Complex> &v, const string filename) {
ofstream output;
output.open(filename, ios::binary);
if (output)
{
for (auto i: v) {
output.write(reinterpret_cast<char*> (&i), sizeof(i));
output << endl;
}
cout << "Wektor zapisany do pliku " << filename << endl;
output.close();
}
else cout << endl << "BLAD TWORZENIA PLIKU BIN" << endl;
}
vector<Complex> readComplexVectorBin(const string &filename) {
vector<Complex> v;
ifstream input;
input.open(filename, ifstream::binary);
if (input) {
Complex line;
while (input.read(reinterpret_cast<char*> (&line), sizeof(Complex))) {
v.push_back(Complex(line));
}
input.close();
}
else cout << endl << "BLAD ODCZYTU PLIKU" << endl;
return v;
}
应该显示:
26.697 + 7.709i
20.133 + 23.064i
9.749 + 8.77i
相反,它显示:
26.697 + 7.709i
1.43761e-57 + 1.83671e-43i
1.26962e+306 + -2.39343e-259i
解决方案
您的问题是您要在二进制文件中插入换行符。
output << endl;
将数据添加到您的文件中
while (input.read(reinterpret_cast<char*> (&line), sizeof(Complex))) {
v.push_back(Complex(line));
}
没有考虑到。您要么需要摆脱output << endl;
写作循环(最简单的解决方案),要么读入并丢弃阅读循环中的换行符(最难的解决方案)。
推荐阅读
- javascript - typescript 如何在 html 脚本标签中获取类型
- django-rest-framework - Django Q 不能使用字符串和 DRF
- css - 使用 Bootstrap 4.4、Wordpress 和 Bootstrap Shortcodes Ultimate 插件的 Flexbox 列等高
- javascript - Fullpage.js 将手动滚动到最近的部分
- javascript - 如何导入 vue js 组件?
- javascript - 如何比较两个不同的 Firestore 查询?
- mysql - MySQL,在存储过程中使用 CONCAT 的问题
- docker - DockerOperator 气流中的 Execution_date
- python - 我必须从给定的 Dataframe 中获取“True”值多于“False”值的组:
- python - 如何使用 Pandas 的条件删除数据框中的某些行?