/*
* 一个简单的目录浏览器
*/
#include
#include
#include
#include
#include
#include
void printdir(char *dir, int depth) {
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(dir)) == NULL) {//打开当前目录
fprintf(stderr, "cannot open directory: %s/n", dir);
return;
}
chdir(dir);//切换目录
while ((entry = readdir(dp)) != NULL) {//获取下一个目录项的有关资料
lstat(entry->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); //递归调用
} else
printf("%*s%s/n", depth, "", entry->d_name);
}
chdir(".."); //返回上层目录
closedir(dp);
}
/*
int main()
{
printf("Directory scan of /home:/n");
printdir("/home",0);
printf("done./n");
exit(0);
}*/
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);
}