opendi(3)/readdir(3)/closedir(3)
用于遍历目录数据块中的记录。opendir打开目录,返回目录DIR *指针代表这个目录,类似FILE *指针句柄,closedir用于关闭句柄DIR *指针传给readdir读取目录数据块中的记录,每次返回一个方向struct dirent反复阅读的指针可以遍历所有记录,所有记录完成后readdir返回NULL。strcut dirent定义如下:
struct dirent{
ino_t d_ion; /*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*/
char d_name[256]; /*filename*/
};
实现简单ls代码演示如下:
#include "./common/head.h" /*功能: *实现简单ls -R功能,打印目录内容,遍历。 */ ///用于遍历打印目录的内容 void printDir(char * dirname){ char pathname[1024]; DIR *dir; struct dirent *dp; struct stat st; if(!(dir = opendir(dirname))){ perror("opendir"); exit(1); } while(dp = readdir(dir)){ if( !strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ) continue; //当目录是.或..读取下一个记录,避免错误 sprintf(pathname, "%s/%s", dirname, dp->d_name); ///字符串拼接 if( stat(pathname, &st) < 0 ){ perror("stat"); exit(1); } if(S_ISDIR(st.st_mode)){ // printDir(pathname); } ///运行到这里,代表不是目录,打印内容 printf("%s\t", dp->d_name); putchar(10); closedir(dir); } } int main(int argc, char *argv[]) { if(argc != 2){ printf("usage:cmd path\n"); return 1; } DIR *dir; if( !(dir = opendir(argv[1])) ){ //opendir打开失败返回NULL perror("opendir"); exit(1); } printDir(argv[1]); return 0; }