2

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)
{
    //...
}
  • 7
    looks like you want [`rewinddir`](https://man7.org/linux/man-pages/man3/rewinddir.3.html). Whether you _need_ to or not .. ? Completely depends on what you're trying to do, add more context. – yano May 19 '23 at 17:01
  • 3
    Beware of [TOCTOU](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use) bugs - you're not guaranteed to get the same results the second time through the directory. – Andrew Henle May 19 '23 at 17:20

1 Answers1

1

To restart the directory enumeration, you can either:

  • use rewinddir()
  • use seekdir() to position the handler back to a previous position retrieved with telldir()
  • close the directory handle with 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)
    {
        //...
    }
chqrlie
  • 131,814
  • 10
  • 121
  • 189