This function is the reentrant version of readdir
. Like
readdir
it returns the next entry from the directory. But to
prevent conflicts between simultaneously running threads the result is
not stored in statically allocated memory. Instead the argument
entry points to a place to store the result.
The return value is 0
in case the next entry was read
successfully. In this case a pointer to the result is returned in
*result. It is not required that *result is the same as
entry. If something goes wrong while executing readdir_r
the function returns a value indicating the error (as described for
readdir
).
If there are no more directory entries, readdir_r
's return value is
0
, and *result is set to NULL
.
Portability Note: On some systems readdir_r
may not
return a NUL terminated string for the file name, even when there is no
d_reclen
field in struct dirent
and the file
name is the maximum allowed size. Modern systems all have the
d_reclen
field, and on old systems multi-threading is not
critical. In any case there is no such problem with the readdir
function, so that even on systems without the d_reclen
member one
could use multiple threads by using external locking.
It is also important to look at the definition of the struct
dirent
type. Simply passing a pointer to an object of this type for
the second parameter of readdir_r
might not be enough. Some
systems don't define the d_name
element sufficiently long. In
this case the user has to provide additional space. There must be room
for at least NAME_MAX + 1
characters in the d_name
array.
Code to call readdir_r
could look like this:
union
{
struct dirent d;
char b[offsetof (struct dirent, d_name) + NAME_MAX + 1];
} u;
if (readdir_r (dir, &u.d, &res) == 0)
...