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).
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.