Reputation: 567
DIR *ptr;
struct dirent *ent, ent2;
int n=0, i=0;
dir = ".";
ptr = opendir(dir);
while((ent = readdir(ptr)) != NULL)
{
if(ent -> d_type != DT_DIR)
{
n++;
}
}
char array[n][100];
while((ent2 = readdir(ptr)) != NULL)
{
if(ent2 -> d_type != DT_DIR)
{
strcpy(array[i], ent2 -> d_name);
i++;
}
}
In the above C code I tried to count the number of files excluding folders in the working directory. Then use the count to declare a double char array which is then used to store the file names. I need to declare the double array knowing the number of files.(not allowed declare a large array). The code works fine when I declare the double array with a large size and a just copy the file names to it without any counting. As I understand, the variable ent is changed within the first while loop. That's the reason I used a different "struct dirent ent2".
Upvotes: 0
Views: 4789
Reputation: 206909
The problem isn't the use of the same variable to store the result of readdir
- that's perfectly fine.
Your issue is that readdir
advances the position of the DIR *
you're using each time you call it. Once you've seen all the files, that directory pointer can't be advanced any more. It doesn't loop back to the beginning.
You can use rewinddir
to reset it to the first entry in the directory. (Or close it and reopen it.)
Upvotes: 6