Francis Glassborow <
francis.g...@btinternet.com> writes:
> On 22/04/2013 12:55, Bertram wrote:
>> I read filenames present in folder with:
>>
>> DIR *dir;
>> struct dirent *ent;
>>
>> if ((dir = opendir ("C:\\")) != NULL) {
>> while ((ent = readdir (dir)) != NULL) {
>> printf ("%s\n", ent->d_name);
>> }
>> closedir (dir);
>>
>> But how do copy filenames in char array?
>>
>> char *namefilesinfolder[100];
>
> That declares an array of 100 pointers to char. I doubt that is what you
> intended.
Since he's reading multiple file names, I suspect it is what he intended.
> Omit the asterisk and one source of error goes, I cannot comment on the
> rest as you are using a POSIX extension to C.
>>
>> strcpy(namefilesinfolder,ent->d_name); // don't work.
ent->d_name gives you a pointer to a string containing a file name. You
call it repeatedly, so you'll get multiple strings.
You have an array of pointers to char. You can make each char* element
of that array point to a string. But you have to allocate space for the
string.
You can't just assign the pointer value of ent->d_name to successive
elements of namefilesinfolder, because each call to readdir() can
clobber the memory used by the previous call; you have to allocate space
for each string and copy the string itself.
In the body of your loop, you could write something like:
namefilesinfolder[index] = malloc(strlen(ent->d_name) + 1);
if (namefilesinfolder[index]) {
/* malloc failed, handle error somehow; do *not* just keep going */
}
strcpy(namefilesinfolder[index], ent->d_name);
index ++;
This is similar to what the non-standard strdup() function does
(non-standard in the sense that it's defined by POSIX but not by
the C standard).
I've ignored the possibility that there are more than 100 files in
the directory. You shouldn't.
--
Keith Thompson (The_Other_Keith)
ks...@mib.org <
http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"