From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 20392 invoked by alias); 26 Dec 2011 11:48:43 -0000 Received: (qmail 20382 invoked by uid 22791); 26 Dec 2011 11:48:41 -0000 X-SWARE-Spam-Status: No, hits=-2.5 required=5.0 tests=AWL,BAYES_00,DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,FREEMAIL_FROM,RCVD_IN_DNSWL_LOW X-Spam-Check-By: sourceware.org Received: from mail-we0-f175.google.com (HELO mail-we0-f175.google.com) (74.125.82.175) by sourceware.org (qpsmtpd/0.43rc1) with ESMTP; Mon, 26 Dec 2011 11:48:28 +0000 Received: by werm13 with SMTP id m13so5585607wer.20 for ; Mon, 26 Dec 2011 03:48:27 -0800 (PST) MIME-Version: 1.0 Received: by 10.216.132.8 with SMTP id n8mr18877993wei.35.1324900107574; Mon, 26 Dec 2011 03:48:27 -0800 (PST) Received: by 10.216.69.7 with HTTP; Mon, 26 Dec 2011 03:48:27 -0800 (PST) In-Reply-To: References: <1324861286.2539.24.camel@debian> Date: Mon, 26 Dec 2011 11:57:00 -0000 Message-ID: Subject: Re: string in structure and fread() From: Jonathan Wakely To: =?ISO-8859-1?Q?Juan_Ram=EDrez?= Cc: Mohsen Pahlevanzadeh , gcc-help Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable X-IsSubscribed: yes Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org X-SW-Source: 2011-12/txt/msg00237.txt.bz2 2011/12/25 Juan Ram=EDrez: > 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: > > =A0 =A0 #define FIELD_LENGTH =A0 101 > > =A0 =A0 struct book { > =A0 =A0=A0=A0 =A0=A0char name[FIELD_LENGTH]; > =A0 =A0=A0=A0 =A0=A0char author[FIELD_LENGTH]; > =A0 =A0=A0=A0 =A0=A0char publisher[FIELD_LENGTH]; > =A0 =A0=A0=A0 =A0=A0char translator[FIELD_LENGTH]; > =A0 =A0=A0=A0 =A0=A0bool translation; > =A0 =A0=A0=A0 =A0=A0bool stock; > =A0 =A0=A0}; 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.