递归列出指定目录下所有的普通文件
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 ;
}
知识点:
普通文件(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 ;
}
相关文章推荐
- 递归列出指定目录内的所有文件夹和文件
- 递归列出指定目录下所有的符号链接文件
- 递归列出指定目录下的所有文件的绝对路径
- 递归列出所有文件和目录
- php递归列出所有文件和目录的代码
- 递归列出所有文件和目录
- Perl脚本递归替换所有指定目录指定文件类型中的指定模式
- 算法:递归列出一个目录下面的所有文件
- 取得指定路径下所有目录及文件名称(递归)
- 列出目录下所有文件包括子目录的文件路径-采用递归方式
- 查找指定目录下所有文件(包括子目录)——使用递归
- 树型结构列出指定目录里所有文件的PHP类
- 当url中未明确指定文件名时,是否列出相关目录下所有文件的开关设置
- 用C#列出指定目录下的所有指定扩展名(多个扩展名)的文件
- [Linux C]列出指定目录下的所有文件(夹)
- l列出目录下的所有文件(递归)
- 【原创】C# 递归获取指定目录的子目录及其所有文件
- asp.net 删除文件夹,指定文件夹,删除文件夹和所有文件,删除权限设置,递归删除文件夹目录及文件
- 列出指定目录下的所有文件和目录
- 列出指定目录下的所有文件和目录