Question

code looks like this:

struct Dog {
  string name;
  unsigned int age;
};

int main()
{
    Dog d = {.age = 3, .name = "Lion"};
    FILE *fp = fopen("dog.txt", "wb");
    fwrite(&d, sizeof(d), 1, fp);   //write d into dog.txt
}

My problem is what's the point of write a data object or structure into a binary file? I assume it is for making the data generated in a running program persistent, right? If yes, then how can I get the data back? Using fread?

This makes me think of database-like stuff, dose database write data into disk the same way?

Was it helpful?

Solution

You can do it but you will have a lot of issues to care about:

  • structure types: all your data needs really be into struct or you can just writing a pointer to some other place.
  • structure changes: if you need change your structure you will need write a converter to read old struct and write the new.
  • language interoperability: will be hard to access the data using other language

It was a common practice in the early days before relational databases popularization. You can make index files pointing to a record number.

However nowadays I will advice you to make serialization and write strings instead binaries.

NOTE: if string is something like char[40] your code maybe will survive... but if your question is about C++ and string is a class then kill you child before it grows up! The string object characters are not into your struct but in the heap.

OTHER TIPS

Writing data in binary is extremely useful and much faster then reading/writing in text, take for instance video games (Although not every video game does this), when the game is saved all of the nescessary structures/classes and other data are written into a save file in binary.

It is just one use for using binary, but the major reason for doing this is speed.

And to read the data back, you will need to know the format that you saved it in, for instance as a simple example, if I saved an integer, char array of n size, and a boolean, I would need to read the binary file in as an integer, char array of n size, and a boolean. Otherwise the data is read improperly and will not be very useful at all

Be careful. The type of field 'name' in your structure is 'string'. This class contains data allocated dynamically. So writing 'string' data into file this way only pointers will be writed, not data itself.

The C++ Middleware Writer supports binary serialization to/from files.

From a marshalling perspective the "unsigned int age" member of your struct is a potential problem. I'd consider changing the type to uint32_t.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top