繁体   English   中英

模板化读/写二进制文件

[英]Templated reading/writing of binary files

所以,我一直试图用以下方式自动化二进制文件在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&的情况下这并不安全。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM