簡體   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