简体   繁体   English

使用文件的指针读取/编写地图C ++

[英]Reading/Writing a map with pointers to a file c++

I'm trying to read and write a std::map object to/from a file. 我正在尝试将std :: map对象读写到文件中。 the map type is 地图类型是

map<string, Node*>

and i have successfully written it to a file but unsuccessfully read it back. 而且我已经成功地将其写入文件,但未成功读回。 i'm not sure if i'm storing it correctly i think it's because i have pointers in the map (Node*) but i'm not sure. 我不确定我是否正确存储它,我认为这是因为我在地图(Node *)中有指针,但是我不确定。 how can i fully write the entire map with all the objects it contains and then read it back perfectly. 我怎么能完整地写出包含所有对象的整个地图,然后完美地读回来。 my current read/write methods are 我目前的读写方法是

Read

template<typename T>
T ReadObject(string path) {
    T num;
    ifstream infile;
    infile.open(path, ios::in|ios::binary);
    infile.read(reinterpret_cast<char *>(&num),sizeof(T));
        infile.close();
    return num;
}

Write

template<typename T>
void WriteObject(string path, T& num) {
       ofstream outfile;
       outfile.open (path, ios::out|ios::binary);
       outfile.write(reinterpret_cast<char *>(&num),sizeof(T));
       outfile.close();
}

btw these work when reading and writing integers 顺便说一下,这些工作在读写整数时有效

Pointers are just memory addresses. 指针只是内存地址。 The data you're pointing to is never being placed into the file. 您指向的数据永远不会放入文件中。

You need to use what you know about the internal structure of the objects when saving them. 保存对象时,需要使用对对象内部结构的了解。 Bitwise copy is not sufficient. 按位复制是不够的。

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

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