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

How to write pointers of an object into a file?

本文关键字:文件 指针 对象      更新时间:2023-10-16

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

现在我这样写/读:

    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指向的任何内容(如果它还不是有效指针,则失败)。