I've got a part of my memory that I want to dump to a file. One reason is to save the information somewhere, and another is to read it again when my program restarts.
What is the proper way of doing this?
My first thought was:
char* start = my_pointer;
int i;
for (i = 0; i < MEMORY_SIZE; i++) {
// write *start to file
start++;
}
Can I write it all as characters? And then use something like this to restore it to memory.
//loop
*my_pointer = fgetc(f);
my_pointer++;
Will my "datastructures" survive as "charachters", or do I need to write it in some sort of binary / hexa data-mode? Or is it a stadard way of doing this?
This problem is called "serializing" and can range from trivial to really complicated. If your data structure is self contained, for instance a bunch of pixels in an array and you know the array dimensions, you can just dump the data out and then read it back.
If you have for instance linked lists, or pointers of any kind, in your data, then those pointers will not point to anything valid once you read them back. This is where a more formal approach to serializing starts to make sense.
This can range from saving as file formats, use databases, convert to XML or other hierarchical format and so on. What is an OK solution depends completely on what kind of data you have, and what types of operations you are doing on it plus how often you plan to write and then read back from disk. (Or network. Or whatever you are doing.)
If what you have is a trivial blob of data, and you just want to write it out the simplest way possible, use fwrite():
fwrite(my_pointer, MEMORY_SIZE, 1, fp);
and then fread() to read the data back. Also see a related (more or less related depending on how advanced your needs are) serializing question on StackOverflow.
Proper serialization also solves the problems that appear when different kinds of CPUs are supposed to be able to read data from each other. Proper serialization in C is lot more complicated than in other languages. In Lisp for instance, all data and code is already serialized. In Java, there are methods to help you serialize your data. The properties of C that makes it a suitable language for high performance and systems programming also makes it tougher to use for some other things.
If you're on a unixy style system memmap and memcpy might give you neat solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With