所以,我一直在尝试通过以下方式在 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;
}
预期输出为“1”;但是,此应用程序在屏幕上显示任何内容之前就崩溃了。更具体地说,就在 writeinto 函数内部。
我可以解释原因吗?如果可能的话,可以提供解决方案吗?
最佳答案
您需要获取对象的地址:
#include <memory>
os.write(reinterpret_cast<char const *>(std::addressof(obj)), sizeof(Type));
// ^^^^^^^^^^^^^^^^^^^
在紧急情况下,您也可以说 &obj
,但在存在重载的 operator&
时这并不安全。
关于c++ - 二进制文件的模板化读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13215856/