string in structure and fread()

Jonathan Wakely
Mon Dec 26 11:57:00 GMT 2011

2011/12/25 Juan Ramírez:
> Hi,
> If you want to write and read a raw structure to a file, using c++
> objects is NOT recommended at all! At least not using fread/fwrite

What do you mean by "c++ objects"?

A POD struct is a "c++ object"

Assuming you mean non-POD class types with non-trivial constructors
and/or non-POD members, I strongly disagree, there is nothing wrong
with doing IO with suh types, you just need to write the IO code
correctly, which is always true.

> Given that fields have fixed length, a good solution could be using a
> raw char array, something like this:
>     #define FIELD_LENGTH   101
>     struct book {
>         char name[FIELD_LENGTH];
>         char author[FIELD_LENGTH];
>         char publisher[FIELD_LENGTH];
>         char translator[FIELD_LENGTH];
>         bool translation;
>         bool stock;
>     };

That solution is useless if the strings can be arbitrarily long, a
better solution is to store the strings in the file as
null-terminated, or length-prefixed, and in either of those cases
managing the strings in the program will be simpler with std::string.

More information about the Gcc-help mailing list