Re: string in structure and fread()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> 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@xxxxxxxxx>:
> 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.



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux