简体   繁体   English

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

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

I have a situation where I need to store an object's pointer into an file and read it again in the same process. 我遇到一种情况,需要将对象的指针存储到文件中,然后在同一过程中再次读取它。 How should I do it? 我该怎么办?

Right now I write/read like this: 现在,我这样写/读:

    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)

I don't see correct values when reading back. 回读时看不到正确的值。 I will read and write these files in the same address space. 我将在相同的地址空间中读取和写入这些文件。

To read and write the pointer itself, you'll need to pass its address, not the address it points to: 要读写指针本身,您需要传递其地址,而不是其指向的地址:

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

You're instead writing the first few bytes of whatever class points to, then trying to read them back into whatever class_read points to (failing if it's not yet a valid pointer). 相反,您正在写任何class指向的前几个字节,然后尝试将它们读回任何class_read指向(如果它不是有效的指针,则失败)。

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

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