简体   繁体   中英

How to write pointer of a struct type in file in C++

This is a c++ Code. I want to write a pointer to a struct in file. When I try to do so it generates an error. I did is >> obj1[0].contentAdress; in main.

struct node3{
    node3(){
        nextContent = NULL;
        for (int i = 0; i<1020; i++)
            content[i] = '\0';
    }
    char content[1020];
    node3* nextContent;
};

//-------------------------------------------------------------------------------------------

struct node1{
    node1(){
        for (int i = 0; i<496; i++)
            fileName[i] = '\0';
    }

    char fileName[496];
    node3* contentAdress;
};

//-------------------------------------------------------------------------------------------

int main(){

    node1 obj1[2097];
    node3 obj3[8192];


        ifstream is("file.txt");
//I want the obj1[0].content Address to be written in file. For that I did:
        **is >> obj1[0].contentAdress;** *THIS GENERATES AN ERROR*

        return 0;
    }

ERROR:

error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'node3 *' (or there is no acceptable conversion)

Cast this to an uint32 (or uint64 on a 64-bit system). But probably it is not what you want, because there is very few cases if a pointer needs to be written in a file.

This error occurs because you did not overload the >> operator to be used with your custom object. The operator can't know how to read your data structure from a file and the opposite is true (it wouldn't know how to output it to a file either).

One option that is available to you if you want to read and write data structures from and to files is a process called serialization which takes a data structure and turns it into symbols that can be read / written to a file (roughly).

http://en.wikipedia.org/wiki/Serialization

"recursively serializing nested structs" refers to the fact that your data structure contains pointers to other instances of the same type thus creating a chain. You would need to recursively traverse all nodes in order to obtain all data about your data structure and be able to serialize it.

Also note that it would not be useful to just output the pointer address to a file because there is no guarantee whatsoever about what will be in the memory space next time your program is run. You absolutely have to store the data.

Another way to achieve this would be to store your data as readable text like in an XML file, for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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