1. 程式人生 > >linux C 遞迴找出一個路徑下的所有檔案

linux C 遞迴找出一個路徑下的所有檔案

#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

void dir_oper(char const*path);

int main(int argc, char const *argv[])
{
	char const*path = argv[1];
	struct stat s_buf;

	/*獲取檔案資訊,把資訊放到s_buf中*/
	stat(path,&s_buf);

	/*判斷輸入的檔案路徑是否目錄,若是目錄,則往下執行,分析目錄下的檔案*/
	if(S_ISDIR(s_buf.st_mode))
	{
		dir_oper(path);
	}

	/*若輸入的檔案路徑是普通檔案,則列印並退出程式*/
	else if(S_ISREG(s_buf.st_mode))
	{
		printf("[%s] is a regular file\n",path);
		return 0;
	}

	return 0;
}

void dir_oper(char const*path)
{
	printf("[%s] it is a dir\n",path);
	struct dirent *filename;
	struct stat s_buf;
	DIR *dp = opendir(path);

	/*readdir()必須迴圈呼叫,要讀完整個目錄的檔案,readdir才會返回NULL
	若未讀完,就讓他迴圈*/
	while(filename = readdir(dp))
	{
		/*判斷一個檔案是目錄還是一個普通檔案*/
		char file_path[200];
		bzero(file_path,200);
		strcat(file_path,path);
		strcat(file_path,"/");
		strcat(file_path,filename->d_name);
		
		/*在linux下每一個目錄都有隱藏的. 和..目錄,一定要把這兩個排除掉。因為沒有意義且會導致死迴圈*/
		if(strcmp(filename->d_name,".")==0||strcmp(filename->d_name,"..")==0)
		{
			continue;
		}

		/*獲取檔案資訊,把資訊放到s_buf中*/
		stat(file_path,&s_buf);

		/*判斷是否目錄*/
		if(S_ISDIR(s_buf.st_mode))
		{
			dir_oper(file_path);
			printf("\n");
		}

		/*判斷是否為普通檔案*/
		if(S_ISREG(s_buf.st_mode))
		{
			printf("[%s] is a regular file\n",file_path);
		}
	}
}