readdir, readdir_r - 读一个目录
readdir函数:
struct dirent *readdir(DIR *dirp);
The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.
成功时,readdir() 返回指向 dirent 结构的指针。(这个结构是静态分配的;不要试图去free(3) 它。)如果到达了上当结尾,NULL 被返回并保持ERRNO不变。如果错误发生了,NULL 被返回并小心设置 ERRNO值。
readdir函数为非线程安全函数;
解决方法:
1、加锁;
2、用局部变量保存数据。
readdir_r()就是采用局部变量保存数据;
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.
readdir_r() 函数是 readdir() 函数可重入版本。它从目录流dirp 里读取下一个目录项,并且通过调用者分配的缓存区 entry返回。返回条目的指针被放置于 *result 里;如果目录流到达结尾,那么把*result 设置为 NULL。
#include <iostream> #include <dirent.h> using namespace std; int main() { struct dirent *pStResult = NULL; 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; }
C++ readdir、readdir_r函数,布布扣,bubuko.com