Mail Archives: djgpp/2001/12/03/07:36:48
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 -