This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: string in structure and fread()
> What do you mean by "c++ objects"?>> A POD struct is a "c++ object"
of course, that's out of the question here
> 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
I know you are right, but looking at Mohsen's code I can tell that he
has not a C++ guru, and getting into the that could lead to a lot of
problems.
In order to use c++ string he should resize the string to the fixed
length of 101 and then perform a call to fread using &str[0] (to treat
is as an array), the same behavior if vector<char> is used.
> 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.
Well, I made that only because Mohsen said strings have fixed length.
Regards
Saludos!
 Â Juan
2011/12/26 Jonathan Wakely <jwakely.gcc@gmail.com>:
> 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.