/*
功能:演示了利用C语言递归遍历指定目录下的子目录(不含隐藏目录)和文件,并以目录树形式展示!
其中编译命令为:gcc -o travel travel.c -std=c99
*/
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
void List(char *path, int level)
{
struct dirent *ent = NULL;
DIR *pDir;
if((pDir = opendir(path)) != NULL)
{
while(NULL != (ent = readdir(pDir)))
{
if(ent->d_type == 8) // d_type:8-文件,4-目录
{
for(int i = 0; i < level; i++)
printf("--");
printf("%s\n", ent->d_name);
}
else if(ent->d_name[0] != '.')
{
for(int i = 0; i < level; i++)
printf("+ ");
char *p = malloc(strlen(path) + strlen(ent->d_name) + 2);
strcpy(p, path);
strcat(p, "/");
strcat(p, ent->d_name);
printf("%s\n", ent->d_name);
List(p, level+1); // 递归遍历子目录
free(p);
}
}
closedir(pDir);
}
}
int main()
{
char path[] = "/home/zcm/program/eclipse";
List(path, 0);
return 0;
}