jeudi 18 mars 2021

Why does fstream not working correctly when I'm trying to use read and write?

I'm trying to create a local file database using fstream and map. I'm using class fstream to read and write. But it is creating an empty file, I tried with operator >>, << and with function read(), write(). And it also not working.

Here is code:

#include <iostream>
#include <map>
#include <fstream>
#include <string>
using str = std::string;
class MapDB{
    public:
        MapDB(str path){
            this->dbfile.open(path, std::fstream::in | std::fstream::out | std::fstream::trunc);
        }
        void PushValue(str key, str value){
            this->Load();
            this->db[key] = value;
            this->Save();
        }
        str GetValue(str key){
            this->Load();
            return this->db[key];
        }
        void RemoveKey(str key){
            this->db.erase(key);
            this->Save();
        }
        ~MapDB(){
            this->dbfile.close();
        }
    private:
        void Load(){
            //this->dbfile.read((char*)&this->db, sizeof(MapDB));
            this->dbfile >> (char*)&this->db;
        }
        void Save(){
            this->dbfile.clear();
            //this->dbfile.write((char*)&this->db, sizeof(MapDB));
            this->dbfile << (char*)&this->db;
        }
        std::fstream dbfile;
        std::map<str, str> db;
};
int main(int argc, char *argv[]){
    std::map<str, str> mydb;
    MapDB mydata("/path/to/file/data.data");
    mydata.PushValue("key", "value");
    std::cout << mydata.GetValue("key") << std::endl;
}

any ideas?

Aucun commentaire:

Enregistrer un commentaire