0

因此,我一直在尝试通过以下方式在 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 函数内部。

我可以解释为什么,如果可能的话,一个解决方案?

4

1 回答 1

2

您需要获取对象的地址

#include <memory>

os.write(reinterpret_cast<char const *>(std::addressof(obj)), sizeof(Type));
//                                      ^^^^^^^^^^^^^^^^^^^

在紧缩中你也可以说&obj,但是在超载的情况下这是不安全的operator&

于 2012-11-04T03:47:06.890 回答