天天看点

linux系统上如何用c代码快速完成目录遍历

    使用c代码完成目录遍历一般常用的方式有两种,一种是递归方式,另一个是链表方式。

    可供使用的api就是opendir、readdir等。其实在glibc中有一种api封装了opendir、readdir等函数,而且是通过链表的方式实现的目录遍历,就是fts_open、fts_read、fts_close等函数。

    其遍历的速度比自己封装实现的还快一些。最、最、最主要的是代码够少,demo code如下:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fts.h>

int main(int argc, char *argv[])
{
    FTSENT *ftsent;
    char * const path[2] = {"/opt", NULL};
    FTS *fts = fts_open(path, FTS_LOGICAL, NULL);
    if ( !fts )
        return -1;
    while ( (ftsent = fts_read(fts)) )  {
        struct stat *stat = ftsent->fts_statp;
        if ( S_ISREG(stat->st_mode) )
            printf("%s是一个普通文件\n", ftsent->fts_accpath);
        else if ( S_ISDIR(stat->st_mode) )
            printf("%s是一个目录文件\n", ftsent->fts_accpath);
    }
    fts_close(fts);
    return 0;
}