1. 程式人生 > >[Linux C]遞迴遍歷指定目錄下的子目錄和檔案

[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