LINUX係統中,遍曆文件夾的函數,C語言版本(在LINUX/Debian上編譯、運行通過),可以遍曆當前目錄以及遞歸遍曆子目錄。
先把代碼放在這裏,方便以後查找!
/*
* ===========================================================================
*
* Filename: main.c
*
* Description: list the files
*
* Version: 1.0
* Created: 2010.12.28
* Compiler: gcc
* Author: puresky
*
* ============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/dir.h>
#include <sys/stat.h>
#include <string.h>
//判斷是否為目錄
int IS_DIR(const char* path)
{
struct stat st;
lstat(path, &st);
return S_ISDIR(st.st_mode);
}
//遍曆文件夾de遞歸函數
void List_Files_Core(const char *path, int recursive)
{
DIR *pdir;
struct dirent *pdirent;
char temp[256];
pdir = opendir(path);
if(pdir)
{
while(pdirent = readdir(pdir))
{
//跳過"."和".."
if(strcmp(pdirent->d_name, ".") == 0
|| strcmp(pdirent->d_name, "..") == 0)
continue;
sprintf(temp, "%s/%s", path, pdirent->d_name);
printf("%s\n", temp);
//當temp為目錄並且recursive為1的時候遞歸處理子目錄
if(IS_DIR(temp) && recursive)
{
List_Files_Core(temp, recursive);
}
}
}
else
{
printf("opendir error:%s\n", path);
}
closedir(pdir);
}
//遍曆文件夾的驅動函數
void List_Files(const char *path, int recursive)
{
int len;
char temp[256];
//去掉末尾的'/'
len = strlen(path);
strcpy(temp, path);
if(temp[len - 1] == '/') temp[len -1] = '\0';
if(IS_DIR(temp))
{
//處理目錄
List_Files_Core(temp, recursive);
}
else //輸出文件
{
printf("%s\n", path);
}
}
int main(int argc, char** argv)
{
if(argc != 2)
{
printf("Usage: ./program absolutePath\n");
exit(0);
}
List_Files(argv[1], 1);
return 0;
}