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

来源:互联网 发布:spss mac 人大 编辑:程序博客网 时间:2024/05/17 23:06

要求:打印输出指定目录下所有普通文件,若文件为子目录,则递归搜索子目录下的普通文件。

知识点:

普通文件(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 ;
}

0 0
原创粉丝点击