繁体   English   中英

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

[英]How to write pointers of an object into a file?

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

现在,我这样写/读:

    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)

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

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

fwrite(&class, sizeof(class), 1, output_file);
fread (&class_read, sizeof(class_read), 1, in_file);
       ^

相反,您正在写任何class指向的前几个字节,然后尝试将它们读回任何class_read指向(如果它不是有效的指针,则失败)。

暂无
暂无

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

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