[英]Templated reading/writing of binary files
So, I've been trying to automatize binary file reading and writing in C++ in the following way (basically, because when handling dynamic data things get specific): 所以,我一直试图用以下方式自动化二进制文件在C ++中的读写(基本上,因为在处理动态数据时,事情是特定的):
#include <iostream>
#include <fstream>
using namespace std;
template <class Type>
void writeinto (ostream& os, const Type& obj) {
os.write((char*)obj, sizeof(Type));
}
template <class Type>
void readfrom (istream& is, const Type& obj) {
is.read((char*)obj, sizeof(Type));
}
int main() {
int n = 1;
int x;
fstream test ("test.~ath", ios::binary | ios::out | ios::trunc);
writeinto(test, n);
test.close();
test.open("test.~ath", ios::binary | ios::in);
readfrom(test, x);
test.close();
cout << x;
}
And the expected output would be of '1'; 而预期的产出将是'1'; this application, however, crashes before anything is show on-screen.
但是,此应用程序在屏幕上显示任何内容之前崩溃。 More specifically, right when inside the writeinto function.
更具体地说,就在writeinto函数内部时。
Could I be explained why and, if possible, a solution? 我可以解释为什么,如果可能的话,解决方案?
You need to take the address of the object: 您需要获取对象的地址 :
#include <memory>
os.write(reinterpret_cast<char const *>(std::addressof(obj)), sizeof(Type));
// ^^^^^^^^^^^^^^^^^^^
In a crunch you can also say &obj
, but that's not safe in the presence of an overloaded operator&
. 在紧缩中你也可以说
&obj
,但是在存在重载operator&
的情况下这并不安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.