嵌入式 Linux系统编程(五)——目录文件函数

    Linux中目录也是文件,目录操作函数为标准IO库函数。主要函数如下:

#include <sys/types.h>

#include <dirent.h>

 

DIR *opendir(const char *name);

DIR *fdopendir(int fd);

成功返回一个指向目录流的指针,失败返回NULL,并且设置errno全局变量。

#include <dirent.h>

 

struct dirent *readdir(DIR *dirp);

成功返回一个指向目录 dirent结构的指针,如果到达目录流结尾或错误返回NULL

        #include <dirent.h>

 

int scandir(const char *dirp,//目录名

struct dirent ***namelist,//返回目录列表

int (*filter)(const struct dirent *),//过滤目录,NULL不过滤

int (*compar)(const struct dirent **,const struct dirent **));//排序返回目录,NULL不排序

    成功返回目录内文件的数量,失败返回-1

目录文件信息结构体dirent

struct dirent {

     ino_t          d_ino;       /* inode number */

     off_t          d_off;       /* offset to the next dirent */

     unsigned short d_reclen;    /* length of this record */

     unsigned char  d_type;      /* type of file; not supported

                                 by all file system types */

     char           d_name[256]; /* filename */

      };

遍历目录函数:

int traverse_dir(const char *path)

{   

    struct dirent **dent;

    unsigned int i = 0;

    i = scandir(path, &dent, NULL, NULL);

    while(*dent)

    {   

        printf("%s\n", (*dent)->d_name);

        dent++;

    }   

    return 0;

}