delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/06/23/06:35:29

Date: Fri, 23 Jun 2000 12:16:57 +0200 (MET DST)
From: pad2369 <pad2369 AT iperbole DOT bologna DOT it>
Message-Id: <200006231016.MAA11944@maggiore.iperbole.bologna.it>
To: djgpp AT delorie DOT com, Ronald Patiño <logan AT cue DOT satnet DOT net>
References: <3952C4BE DOT C9D570E9 AT cue DOT satnet DOT net>
In-Reply-To: <3952C4BE.C9D570E9@cue.satnet.net>
MIME-Version: 1.0
User-Agent: IMP/PHP3 Imap webMail Program 2.0.11
Sender: pad2369 AT iperbole DOT bologna DOT it
Subject: Re: newbie question:Writing a structure to a file
Reply-To: djgpp AT delorie DOT com

Ronald Patiño <logan AT cue DOT satnet DOT net>:

> Im trying to write this structure to a file, and then 
> retrive it from
> another program,
> but i'm having troubles.
> 
> struct db{
>   char  *url;
>   char  test;
> };

Your struct contains a pointer to a string... 
 
> this is the code I use to write data to the file :
> 
> struct db line;
[...] 
>    line.url="http://www.ironmaiden.com";
>    line.test='T';
>    fwrite(&line,sizeof(line),1, data);

Here you are writing the value of the pointer (ie: a 
memory address) and not the value of the string it 
points to.

When you read it from another program, your pointer 
will contain some address which does not refer to the 
same string, and most probably will crash accessing an 
invalid pointer.

You should try something like this :

/* warning: untested code */

struct db{
   char  url[ MAX_URL_LEN ];
   char  test;
};

...

strcpy(line.url, "http://www.ironmaiden.com");
line.test='T';
fwrite(&line,sizeof(line),1, data);

ciao
  Giacomo
-----------------------------------------------------
Giacomo Degli Esposti - pad2369 AT iperbole DOT bologna DOT it

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019