readdir_r()读取目录内容

readdir()在多线程操作中不安全,Linux提供了readdir_r()实现多线程读取目录内容操作。

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main(void)
{
    DIR* dirp;
    struct dirent *dp1=malloc(sizeof(struct dirent));
    struct dirent *dp2=malloc(sizeof(struct dirent));
    dirp=opendir(".");
    while(1)
    {
        if((readdir_r(dirp,dp1,&dp2))!=0)
        {
            perror("readdir_r");
            exit(EXIT_FAILURE);
        }
        if(dp2==NULL)
            break;
        if(dp2->d_name[0]=='.')
            continue;
        printf("inode=%d\t",dp2->d_ino);
        printf("reclen=%d\t",dp2->d_reclen);
        printf("name=%s\n",dp2->d_name);
    }
    close(dirp);
    free(dp1);
    free(dp2);
    return 0;
}

posted on 2014-05-10 11:37  lakeone  阅读(2876)  评论(1编辑  收藏  举报

导航