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	",dp2->d_ino);
        printf("reclen=%d	",dp2->d_reclen);
        printf("name=%s
",dp2->d_name);
    }
    close(dirp);
    free(dp1);
    free(dp2);
    return 0;
}

原文地址:https://www.cnblogs.com/lakeone/p/3720250.html