通过递归调用读取目录和文件信息去遍历整个目录:
示例代码:
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h> void printdir(char * dir, int depth)
{
DIR * dp = opendir(dir);
if (NULL == dp)
{
fprintf(stderr, "cannot open directory: %s\n", dir);
return;
}
chdir(dir);
struct dirent * entry;
struct stat statbuf;
while ((entry = readdir(dp)) != NULL)
{
stat(entry->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode))
{
if (strcmp(".", entry->d_name) == || strcmp("..", entry->d_name) == )
continue;
printf("%*s%s/\n", depth, "", entry->d_name);
printdir(entry->d_name, depth + );
}
else
printf("%*s%s\n", depth, "", entry->d_name);
//printf("%*s",4,"*"); 该函数表示输出"___*",前面输出3个空格。
//如果是printf("%*s",4,"**");则表示输出"__**",前面输出2个空格。
}
chdir("..");
closedir(dp);
} int main(int argc, char * argv[])
{
char * topdir, pwd[] = ".";
if (argc < )
topdir = pwd;
else
topdir = argv[];
printf("Directory scan of %s\n", topdir);
printdir(topdir, );
printf("done.\n");
exit();
}
运行结果: