二进制文件的模板阅读/写作



所以,我一直在尝试以以下方式自动以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&的情况下,这是不安全的。

最新更新