/*功能:演示了在Linux下利用C语言递归遍历指定目录下的子目录(不含隐藏目录)和文件*/#include <stdio.h>#include <dirent.h>#include <string.h>void List(char *path){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-目录printf("File:\t%s\n", ent->d_name);else if(ent->d_name[0] != '.'){printf("\n[Dir]:\t%s\n", ent->d_name);List(ent->d_name);// 递归遍历子目录printf("返回[%s]\n\n", ent->d_name);}}closedir(pDir);}elseprintf("Open Dir-[%s] failed.\n", path);}int main() { char path[] = "/home/zcm/program/test";List(path);return 0; }
程序运行结果:
File:travel.cFile:p1.cFile:1012.log[Dir]:testFile:temp.txtFile:b.cFile:convert2.shFile:d.txtFile:a.cFile:d.cFile:convert1.shFile:tst.cFile:test.sh返回[test][Dir]:whatdirFile:a1.cFile:a2.c返回[whatdir]File:p1File:travelFile:a.shFile:1005.logFile:travel.cppFile:p0File:wht.logFile:ty12.logFile:p2File:1120.logFile:p2.cFile:whatarey.logFile:20011008.logFile:1006.logFile:p0.c