I am working on directories using dirent.h in c and I want to use a couple of loop with
((entry = readdir(folder)) != NULL)
as a condition.
my question is, do I need to somehow reset it to the starting point of he directory again after the loop, and if so, how?
for example :
while ((entry = readdir(folder)) != NULL)
{
//...
}
//and then, use another loop with the same condition
while ((entry = readdir(folder)) != NULL)
{
//...
}
To restart the directory enumeration, you can either:
rewinddir()
seekdir()
to position the handler back to a previous position retrieved with telldir()
closedir()
and reopen it with opendir()
or opendirat()
.Note however these remarks:
Some of the above methods might not be available on all systems, so the last one is probably the most portable alternative.
The second enumeration might produce a different set of entries or in a different order than the first, depending on the system and what concurrent operations may have happened in the interim.
If you rely on the enumeration to produce exactly the same output, you should consider saving the entries during the first enumeration instead of rescanning.
If for example you determine the number of entries in the first scan to allocate an array, you should still check during the second enumeration that you do not get more entries than can fit in the allocated array.
Modified pseudo code:
while ((entry = readdir(folder)) != NULL)
{
//...
}
//and then, use another loop with the same condition
rewinddir(folder);
while ((entry = readdir(folder)) != NULL)
{
//...
}