簡體   English   中英

用C ++保存文件沒有寫入數據

[英]Saving a file in C++ no data written

我有一個成員clientCache的類:

    public:
        LRUCache<string, string>* clientCache;

緩存由以下內容啟動:

    clientCache = new LRUCache<string, string>(3);

    //Reset cache to stored values if exist:
    ifstream ifs(this->cachePath.c_str(), ios::binary);

    // Verify that file exists
    if(ifs.good()){
        ifs.read((char *)&this->clientCache, sizeof(this->clientCache));
        printf("Persistent cache file loaded");
    }

在析構函數中:

    ofstream ofs(this->cachePath.c_str(), ios::binary);
    ofs.write((char *)&this->clientCache, sizeof(this->clientCache));
    printf("Persistent cache file written with:");
    printf((char*)&this->clientCache); //-> Nothing gets printed 

嘗試加載上一步寫入的文件失敗:

    ifstream ifs(this->cachePath.c_str(), ios::binary);
    // Verify that file exists
    if(ifs.good()){
        ifs.read((char *)&this->clientCache, sizeof(this->clientCache));
        printf("Persistent cache file loaded");
    }

打印輸出真的應該是空的嗎? 這是保存失敗的標志嗎? LRUCache類的內容(方法/成員)是否重要,即如果我嘗試存儲所有鍵值而不是整個實例的數據,我會更成功嗎?

你混合std::basic_ostream::writeprintf ,它們是無關的。 write用於未格式化的字符/字節數據輸出,而printf樣式格式的輸出。

此外,您不能將類寫入磁盤並以此方式讀取它,因為對象的二進制布局(尤其是虛函數表的地址)可能因程序的一次運行而異。

在這種特殊情況下,您甚至只能寫入和讀取動態內存的指針。 當您向后讀指針時,它應該指向的內存可能不再被分配。

最好編寫一個合適的輸入和輸出操作符,它只讀取和寫入所需的成員。

printf((char*)&this->clientCache); //-> Nothing gets printed 

我認為這不符合你的要求。 假設clientCache是一個指針

LRUCache<string, string>* clientCache;

會發生什么是打印指針值(應該不起作用),而不是存儲在其中的對象。
無論如何,更好的方法是使用<<>>運算符來編寫和讀取對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM