Readdir, Readdir_r-read a directory
readdir function:
struct dirent *readdir (DIR *dirp);
The data returned by Readdir () is overwritten by subsequent calls to Readdir () for the same directory stream.
Upon success, Readdir () returns a pointer to the dirent structure . (This structure is statically assigned; do not try to go to free (3) it.) If the end is reached, NULL is returned and remains errno unchanged. If the error occurs, NULL is returned and the errno value is carefully set.
The Readdir function is a non-thread safe function;
Workaround:
1, locking;
2. Save the data with local variables.
Readdir_r() is the use of local variables to save data;
int Readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
The Readdir_r() function returns 0 on success. On error, it returns apositive error number (listed under ERRORS). If the end of the directory stream is reached, Readdir_r() returns 0, and returns NULL In*result.
The Readdir_r () function is a readdir () function that can be re-entered version . It reads the next directory entry from the directory stream dirp and returns through the buffer entry allocated by the caller. the pointer to the return entry is placed in *result, and if the directory stream reaches the end, the *result is set to NULL.
#include <iostream> #include <dirent.h>using namespace Std;int main () { struct dirent *pstresult = null;< C1/>struct dirent *pstentry = NULL; int len = 0; DIR *pdir = Opendir ("/home/wzy/owner_lib"); if (NULL = = Pdir) { printf ("Opendir failed!\n"); return 0; } Len = offsetof (struct dirent, d_name) + pathconf ("/home/wzy/owner_lib", _pc_name_max) + 1; Pstentry = (struct dirent*) malloc (len); while (! Readdir_r (Pdir, Pstentry, &pstresult) && pstresult! = NULL) { printf ("File ' name is%s\n", pstentry->d_name); } Free (pstentry); Closedir (pdir); return 0;}