zoukankan      html  css  js  c++  java
  • 用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
    ",buf);
                getdir(buf);
            }
            if(ptr->d_type==DT_REG)
            {
                sprintf(buf,"%s/%s",pathname,ptr->d_name);//把pathname和文件名拼接后放进缓冲字符数组
                printf("文件:%s
    ",buf);
            }
        }
        return 0;
    }
    int main()
    {
        getdir("/home/cpc/Pictures");
        return 0;
    }

    输出结果:

  • 相关阅读:
    PHP 8.0 带来的新特性
    do sth 之 提取了一份文档
    Java入门15---网络编程
    Java入门14---logback
    限流策略
    JConsole 可视化工具
    SpringBoot注解---6.声明式事务
    SpringBoot注解---5.AOP
    SpringBoot注解---4.扩展原理
    SpringBoot注解---2.组件赋值
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/12159336.html
Copyright © 2011-2022 走看看