歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言在Linux下遞歸遍歷文件夾中的文件

C語言在Linux下遞歸遍歷文件夾中的文件

日期:2017/3/1 9:50:16   编辑:Linux編程

C語言在Linux下遞歸遍歷文件夾中的文件

/******************************************
* 作者: chengshuguang
* 版本: 1.0
* 時間: 2013年11月
* 程序說明:
* 輸入:./a.out <dirPaht> 比如:列出home下的所有
* 文件,只需要輸入./a.out /home
******************************************/
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <assert.h>

#define MAX_PATH_LEN 512

int count =0;
char dirPath[MAX_PATH_LEN];

void listAllFiles(char *dirname)
{
assert(dirname != NULL);

char path[512];
struct dirent *filename;//readdir 的返回類型
DIR *dir;//血的教訓阿,不要隨便把變量就設成全局變量。。。。

dir = opendir(dirname);
if(dir == NULL)
{
printf("open dir %s error!\n",dirname);
exit(1);
}

while((filename = readdir(dir)) != NULL)
{
//目錄結構下面問什麼會有兩個.和..的目錄? 跳過著兩個目錄
if(!strcmp(filename->d_name,".")||!strcmp(filename->d_name,".."))
continue;

//非常好用的一個函數,比什麼字符串拼接什麼的來的快的多
sprintf(path,"%s/%s",dirname,filename->d_name);

struct stat s;
lstat(path,&s);

if(S_ISDIR(s.st_mode))
{
listAllFiles(path);//遞歸調用
}
else
{
printf("%d. %s\n",++count,filename->d_name);
}
}
closedir(dir);
}


int main(int argc, char **argv)
{

if(argc != 2)
{
printf("one dir required!(for eample: ./a.out /home/myFolder)\n");
exit(1);
}
strcpy(dirPath,argv[1]);
listAllFiles(dirPath);
printf("total files:%d\n",count);
return 0;
}

Copyright © Linux教程網 All Rights Reserved