delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/11/17/04:34:13

Date: Tue, 17 Nov 1998 11:31:59 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
X-Sender: eliz AT is
To: deseeker <deseeker AT yahoo DOT com>
cc: djgpp AT delorie DOT com
Subject: Re: Array Headache!
In-Reply-To: <72rbd0$h57@news2.jaring.my>
Message-ID: <Pine.SUN.3.91.981117112022.14078V-100000@is>
MIME-Version: 1.0
Reply-To: djgpp AT delorie DOT com

On Tue, 17 Nov 1998, deseeker wrote:

>     ++*fn = dir->d_name;
>   ...
> Somebody would propably laughing already! After a idiotic trial and error, I
> found out that the dir->d_name has the same address each time. So I endup
> getting a list of the same (last)filename in fn b'cos each *fn is the SAME.

Note that this is actually documented in the library reference, under 
`readdir'.  An excerpt:

	Return Value
	------------

	A pointer to a static buffer that is overridden with each call.

> After that, I though of writing the output to a file could solve the
> prob(Haven't try yet) but I don't want to.
> 
> Can anybody help me how to create a large array to hold each filename (IF
> file numbers way way larger)

One way is to allocate the storage as needed with `malloc'.  For example:

	int max_fn = 0;
	char **fn = NULL;
	int i = 0;
	...
 	while((dir = readdir(path)))
	{
	    if (i > max_fn - 1)
	    {
		max_fn += 100;
		fn = (char **)realloc(fn, max_fn*sizeof(char *));
	    }
	    fn[i++] = strdup (dir->d_name);
	}

(`strdup' is not so portable, but you can replace it with a call to 
`malloc' and `strcpy'.)

- Raw text -


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