头文件 #include <dirent.h>
函数一: DIR * opendir(const char * name);
打开指定目录name,返回执行该目录流的指针。 成功:返回指向目录流指针;失败:返回NULL。
函数二: struct dirent * readdir(DIR * dr); 读取目录下的节点信息。 成功:返回指向dirent结构体指针,读取结束或错误返回NULL。
其中结构体dirent为: 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 文件类型 4:目录,8:文件,10:链接文件 char d_name [NAME_MAX+1]; // file name (null-terminated) 文件名,最长255字符 }
函数三: int closedir(DIR * dir); 关闭dir所指的目录流。 成功:返回0;失败:返回-1。
示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 #include <stdio.h> #include <unistd.h> #include <dirent.h> #include <string.h> void traverse(const char* dirPath) { DIR* dir; struct dirent * ptr; if((dir = opendir(dirPath)) == NULL) return; while((ptr = readdir(dir)) != NULL) { if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir continue; if(ptr->d_type == 4) //目录 { char path[256] = {0}; strncpy(path, dirPath, 256); strcat(path, ptr->d_name); printf("目录:%s\n", path); } else if(ptr->d_type == 8) { char path[256] = {0}; strncpy(path, dirPath, 256); strcat(path, ptr->d_name); printf("文件:%s\n", path); } else if (ptr->d_type == 10) { char path[256] = {0}; strncpy(path, dirPath, 256); strcat(path, ptr->d_name); //获取链接的目标 char dst[1024] = {0}; readlink(path, dst, 1024); printf("链接:%s --> %s\n", path, dst); } } closedir(dir); } int main() { traverse("/proc/"); return 1; }