#include<unistd.h>
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<stdlib.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry; //dirent不仅仅指向目录,还指向目录中的具体文件
struct stat statbuf; //stat,lstat,fstat1 函数都是获取文件:普通文件,目录,管道,socket,字符,块()的属性。函数原型#include <sys/stat.h>
// lstat函数与stat类似,但是当文件是一个符号连接时,lstat返回该符号连接的有关信息,而不是由该符号连接引用的文件的信息。
if ((dp=opendir(dir))==NULL){ //opendir来自dirent.h
fprintf(stderr,"cannot open directory: %s\n",dir);
return;
}
chdir(dir); //As you use the cd command in the shell to change directory, so a program can use the chdir system call.
while((entry = readdir(dp))!=NULL){
lstat(entry->d_name,&statbuf); //lstat函数用来连接文件描述名,获取文件属性。
//通过readdir函数读取到的文件名存储在结构体dirent的d_name成员中,属性去到了statbuf。
if (S_ISDIR(statbuf.st_mode)) { //如果读取对象是个目录
if (strcmp(".",entry->d_name) == 0 || //文件名为.或者..其实也就是自己,自然无法再进入。
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);//在当前位置,把文件名打出来
printdir(entry->d_name,depth+4); //递归继续往里走,直到走到尽头只有文件而没有目录。depth这货是专门用来占位的
}
else printf("%*s%s\n",depth,"",entry->d_name); //不是目录的话,直接print名字。depth这货是专门用来占位的,对应%*s,使得打印出来的东西有层次。
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir = "."; //默认当前目录
if (argc >= 2)
topdir=argv[1]; //也可以换目录。
printf("Directory scan of %s\n",topdir);
printdir(topdir,0);
printf("done.\n");
exit(0);
}
最后上个图片子