如何将对象的指针写入文件?

mgr*_*mgr 1 c c++

我有一种情况,我需要将对象的指针存储到一个文件中,并在同一个过程中再次读取它.我该怎么办?

现在我这样写/读:

    Myclass* class  = <valid pointer to Myclass>
    FILE* output_file = fopen(filename, "w");
    fwrite(class, sizeof(class), 1, output_file)

// and read it

    FILE* in_file = fopen(filename, "r");
    Myclass* class_read
    fread(class_read, sizeof(class_read), 1, in_file)
Run Code Online (Sandbox Code Playgroud)

回读时我看不到正确的值.我将在同一地址空间中读取和写入这些文件.

Mik*_*our 5

要读取和写入指针本身,您需要传递其地址,而不是它指向的地址:

fwrite(&class, sizeof(class), 1, output_file);
fread (&class_read, sizeof(class_read), 1, in_file);
       ^
Run Code Online (Sandbox Code Playgroud)

你正在编写任何class点的前几个字节,然后尝试将它们读回到任何class_read点(如果它还不是一个有效的指针则失败).