www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/12/03/07:36:48

X-Authentication-Warning: delorie.com: mailnull set sender to djgpp-bounces using -f
Message-ID: <3C0B7127.5080F19F@eik.bme.hu>
Date: Mon, 03 Dec 2001 13:33:43 +0100
From: "Dr.=?iso-8859-1?Q?Andr=E1s=20S=F3lyom?=" <solyom AT eik DOT bme DOT hu>
Organization: none
X-Mailer: Mozilla 4.75 [en] (Win98; U)
X-Accept-Language: hu,en
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re: Loading data in a single operation?!?
References: <1tbg0uom8q1u46t3eo26cgqv261mahoet4 AT 4ax DOT com>
Reply-To: djgpp AT delorie DOT com

Radical DOT NetSurfer AT delorie DOT com wrote:

> Here's a toughy:
>
> Using conventional C-style code,
> something I wish to be portable,
> how would you load in data for a
> two-dimensional string array...
> dynamically allocated:
>
>

... code snippet cut

>
> HOW CAN I SIMPLY LOAD THE _entire_ FILE
> INTO MEMORY in one swift operation ?
> say, using    fread()   ???
>
> the string array in memory has the actual format
> of:
> char *StringArray1[i] = {
>   "item1a", "item1b",
>  "item2a", "item2b",
>  etc.  etc.
> };
>
> the sizes of each string is unique....
> the size of the array may change the next time
> the program runs,
> any ideas?
>

Store 0 terminated strings  in the file! You than simple read in the the
whole file with fread after
allocating enough space for it (memory size will be 1 more than file
size,determined by stat/fstat). Put a 0 into the last byte of the
allocated buffer. Then run through these strings in memory to get the
number of strings in it and allocate and fill up your array. You can
determine where the array ends utililising the additional 0 you have put
there: if the next string is empty then you have reached the end. Like:
    char *p = buffer;  int count = 0; int i = 0;
    while(*p) { ++count; p = p + strlen(p)+1; }
   StringArray = (char**) calloc(count, sizeof(char*) );
    while(*p) { StringArray[i] = p; ++i; p = p + strlen(p)+1; }

    Andras

- Raw text -


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