用linuxC语言遍历输出文件目录下的文件夹和文件

  • 实验环境linux mint 开发平台 Qt5.11
  • 总体思想,linux C的文件目录相关函数有 mkdir rmdir opendir readdir
  • 文件目录指针类型 DIR*
  • dirent代表系统文件目录相关的结构体,其中属性d_type文件类型 d_name文件名或目录名DT_DIR代表文件目录,DT_REG代表普通文件
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<dirent.h>
#include<sys/types.h>

int getdir(char * pathname)
{
    DIR* path=NULL;
    path=opendir(pathname);

    if(path==NULL)
    {
        perror("failed");
        exit(1);
    }
    struct dirent* ptr; //目录结构体---属性:目录类型 d_type,  目录名称d_name
    char buf[1024]={0};
    while((ptr=readdir(path))!=NULL)
    {
        if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0)
        {
            continue;
        }
        //如果是目录
        if(ptr->d_type==DT_DIR)
        {

            sprintf(buf,"%s/%s",pathname,ptr->d_name);
            printf("目录:%s\n",buf);
            getdir(buf);
        }
        if(ptr->d_type==DT_REG)
        {
            sprintf(buf,"%s/%s",pathname,ptr->d_name);//把pathname和文件名拼接后放进缓冲字符数组
            printf("文件:%s\n",buf);
        }
    }
    return 0;
}
int main()
{
    getdir("/home/cpc/Pictures");
    return 0;
}

输出结果:

猜你喜欢

转载自www.cnblogs.com/saintdingspage/p/12159336.html