[Linux C]递归遍历指定目录下的子目录和文件

/*
	功能:演示了在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);
	}
	else
		printf("Open Dir-[%s] failed.\n", path);
}

int main() 
{         
	char path[] = "/home/zcm/program/test";
	List(path);

	return 0; 
}



程序运行结果:

 

File:	travel.c
File:	p1.c
File:	20111012.log

[Dir]:	test
File:	temp.txt
File:	b.c
File:	convert2.sh
File:	d.txt
File:	a.c
File:	d.c
File:	convert1.sh
File:	tst.c
File:	test.sh
返回[test]


[Dir]:	whatdir
File:	a1.c
File:	a2.c
返回[whatdir]

File:	p1
File:	travel
File:	a.sh
File:	20111005.log
File:	travel.cpp
File:	p0
File:	wht.log
File:	2011ty12.log
File:	p2
File:	20111120.log
File:	p2.c
File:	whatarey.log
File:	20011008.log
File:	20111006.log
File:	p0.c

 

阅读更多
个人分类: Linux_C
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭