您的位置:首页 > 其它

递归列出指定目录下所有的普通文件

2014-06-14 17:51 357 查看
要求:打印输出指定目录下所有普通文件,若文件为子目录,则递归搜索子目录下的普通文件。

知识点:

普通文件(Regular File)。指普通意义上的文件,如数据文件、可执行文件等。与其他类型的文件区别开来。

int stat(const char *restrict pathname, struct stat *restrict buf)

宏定义S_ISREG (st_mode)判断是否为普通文件。

代码:

#include<stdio.h>

#include<stdlib.h>

#include<sys/stat.h>

#include<unistd.h>

#include<errno.h>

#include<dirent.h>

#include<sys/types.h>

#define SIZE 1024

int dir_run(char *path)

{ DIR *dir;

dir = opendir(path);

if (dir == NULL)

{

return -1;

}

struct stat st;

struct dirent *entry;

char fullpath[SIZE];

while((entry = readdir(dir)) != NULL)

{

if((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0))

{

continue;

}

sprintf(fullpath, "%s/%s", path, entry->d_name);

if(stat(fullpath, &st) != 0)

{

continue;

}

if(S_ISREG(st.st_mode))

{

printf("%s\n",entry->d_name);

}

if(S_ISDIR(st.st_mode))

{

dir_run(fullpath);

printf("\n");

}

}

closedir(dir);

return 0;

}

int main(int argc,char*argv[])

{

if(argc!=2)

{

printf("参数不正确!正确格式:./main filepath\n");

exit(1);

}

dir_run(argv[1]);

return 0 ;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: