opendir()函数:
头文件:
#include <sys/types.h>
#include <dirent.h>
函数原型:
Dir* opendir(const char* pathname);
函数功能:
获取pathname目录下的所有文件和目录的列表,如果pathname是个文件或失败则返回NULL,并设置errno
返回值DIR结构体的原型为:struct _dirstream
typedef struct _dirstream DIR;
struct _dirstream
{void* _fd;char* _data;int _entry_data;char* _ptr;int _entry_ptr;size_t _allocation;size_t _size;_libc_lock_define (,_lock)
};
readdir()函数:
头文件:#include <dirent.h>
函数原型:
struct dirent *readdir(DIR *dir_handle);
函数功能:读取opendir返回的那个列表
struct dirent
{long d_ino; /* inode number 索引节点号 */off_t d_off; /* offset to this dirent 在目录文件中的偏移 */unsigned short d_reclen; /* length of this d_name 文件名长 */unsigned char d_type; /* the type of d_name 文件类型 */char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */};
其中d_type文件类型又有如下情况:
enum
{DT_UNKNOWN = 0, //未知类型DT_FIFO = 1, //管道DT_CHR = 2, //字符设备DT_DIR = 4, //目录DT_BLK = 6, //块设备DT_REG = 8, //常规文件DT_LNK = 10, //符号链接DT_SOCK = 12, //套接字DT_WHT = 14 //链接
};
演示示例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>// main 函数的 argv[1] char * 作为 所需要遍历的路径 传参数给 listDir
void listDir(char *path)
{ DIR *pDir;//定义一个 DIR 类的指针struct dirent *ent;//定义一个结构体 dirent 的指针,dirent 结构体见上int i = 0; char childpath[512];//定义一个字符数组,用来存放读取的路径pDir = opendir(path); //opendir 方法打开 path 目录,并将地址付给 pDir 指针memset(childpath, 0, sizeof(childpath)); //将字符数组 childpath 的数组元素全部置零//读取 pDir 打开的目录,并赋值给 ent, 同时判断是否目录为空,不为空则执行循环体while ((ent = readdir(pDir)) != NULL){//读取 打开目录的文件类型 并与 DT_DIR 进行位与运算操作,即如果读取的 d_type 类型为 //DT_DIR (=4 表示读取的为目录)if (ent->d_type & DT_DIR) {if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {//如果读取的 d_name 为 . 或者.. 表示读取的是当前目录符和上一目录符, 用 //contiue 跳过,不进行下面的输出continue;}//如果非. ..则将 路径 和 文件名 d_name 付给 childpath, 并在下一行 prinf 输出sprintf(childpath, "%s/%s", path, ent->d_name);printf("path:%s\n", childpath);//递归读取下层的字目录内容, 因为是递归,所以从外往里逐次输出所有目录(路径+目录名)//然后才在 else 中由内往外逐次输出所有文件名listDir(childpath);}//如果读取的 d_type 类型不是 DT_DIR, 即读取的不是目录,而是文件,则直接输出 d_name, 即输出文件名elseprintf("%s\n", ent->d_name);}
}int main(int argc, char *argv[])
{listDir(argv[1]); //第一个参数为想要遍历的linux目录。例如,当前目录为 ./ ,上一层目录为../return 0;
}