linux中opendir,readdir,closedir的使用

大耗子 2020年03月29日 176次浏览

文章链接:https://codemouse.online/archives/2020-03-29211238

头文件

#include <sys/types.h>
#include <dirent.h>

打开目录

  • opendir函数:传入name路径,成功则返回非空DIR指针,否则返回NULL。

    DIR *opendir(const char *name);
    

读取目录

  • readdir函数:返回 struct dirent *指针,读完目录下所有文件时,返回NULL

    struct dirent *readdir(DIR *dirp);
    
  • readdir_r函数:返回0则成功.读完目录下所有文件时,*result返回NULL

    int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
    // 如果支持readdir_r,建议使用这个,因为readdir不是线程安全的,readdir_r解决了这个问题.
    
  • struct dirent结构体

    struct dirent {
        ino_t          d_ino; /* inode number */
        off_t          d_off; /* not an offset; see NOTES */
        unsigned short d_reclen;  /* length of this record */
        unsigned char  d_type;    /* type of file; not supported
                                 by all filesystem types */
        char           d_name[256]; /* filename */
    };
    
    d_type参数:
        DT_BLK      This is a block device.
        DT_CHR      This is a character device.
        DT_DIR      This is a directory.
        DT_FIFO     This is a named pipe (FIFO).
        DT_LNK      This is a symbolic link.
        DT_REG      This is a regular file.
        DT_SOCK     This is a UNIX domain socket.
        DT_UNKNOWN  The file type is unknown.
    
  • readdir demo

    DIR *pDir = NULL;
    struct dirent * pEnt = NULL;
    
    pDir = opendir("test");
    pEnt = readdir(pDir);
    
  • readdir_r demo

    DIR *pDir = NULL;
    
    struct dirent * pEnt = NULL;
    struct dirent * result = NULL;
    
    pDir = opendir("test");
    readdir_r(pDir, pEnt, &result);
    

关闭目录

  • closedir函数:关闭掉打开的目录.

    int closedir(DIR *dir);