当前位置: 首页 > article >正文

Linux:linux系统中目录的遍历

Linux系统中目录的遍历

  • 1、Linux中目录的遍历
    • (1)函数opendir
    • (2)函数readdir
    • (3)函数closedir
    • (4)遍历指定目录的所有文件和子目录

1、Linux中目录的遍历

(1)函数opendir

打开需要被遍历的目录

DIR *opendir(const char *pathname);
  • pathname:待遍历的目录
  • return:成功则返回目录结构体指针,失败返回NULL

(2)函数readdir

依次读取目录结构体中的数据

dirent *readdir(DIR *dir);
  • dir:opendir返回的结构体指针
  • return:成功则返回当前目录下文件或文件夹的结构体,失败则返回NULL

(3)函数closedir

关闭opendir打开的dir目录

int closedir(DIR *dir);
  • dir:opendir返回的目录指针
  • return:成功返回0,失败返回-1

(4)遍历指定目录的所有文件和子目录

以下函数可以直接使用,目录下的所有子目录和文件都会被写入到txt文件中:

#include <sys/types.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
#include <unistd.h>
#include <dirent.h>
int ReadCurDir(const char *pathname,int fd)
{
        DIR *dir = opendir(pathname);
        if(dir==NULL){
                printf("Failed to open dir!");
                return 0;
        }
        dirent *ptr_dir=NULL;
        while(NULL!=(ptr_dir = readdir(dir))){
                if(strcmp(ptr_dir->d_name,".")==0||strcmp(ptr_dir->d_name,"..")==0){
                        continue;
                }
                char strLine[1024];
                sprintf(strLine,"%s/%s\n" , pathname,ptr_dir->d_name);
                printf("%s",strLine);
                write(fd,strLine,strlen(strLine));
                if(ptr_dir->d_type==DT_DIR){
                        char newPath[1024];
                        sprintf(newPath,"%s/%s",pathname,ptr_dir->d_name);
                        ReadCurDir(newPath,fd);
                }
        }
        closedir(dir);
        return 1;
}

http://www.kler.cn/news/351186.html

相关文章:

  • 类加载器介绍
  • Selenium自动化测试工具
  • 安装Python及pip使用方法详解
  • 推荐IDE中实用AI编程插件,目前无限次使用
  • 《黑神话悟空》各章节boss顺序汇总
  • uniapp结合uview-ui创建项目
  • Dockerfile构建Docker镜像
  • 【ChatGPT】什么是ChatGPT:基础介绍与使用场景
  • 每天住院人数
  • QUIC(Quick UDP Internet Connections)与 RTMP(Real Time Messaging Protocol)
  • springboot集成pdfbox解析pdf文件
  • 最近项目的笔记总结。
  • 私有变量、类函数、断言assert
  • vue播放flv和rtsp 格式视频
  • 找到你的乐趣,这六个网站不容错过!
  • 【算法题】62. 不同路径(LeetCode)
  • 安装vue发生异常:npm ERR! the command again as root/Administrator.
  • Docker 下安装 ElasticSearch 和 Kibana (单节点)
  • Python办公自动化案例:实现word表格转换成Excel表格
  • 【MySQL】入门篇—基本数据类型:使用WHERE子句进行数据过滤
  • conda新建环境中存在大量ros相关python包
  • SpinalHDL之设计错误(Design Errors)(二)
  • Sequelize 提示报错ERR_HTTP_HEADERS_SENT
  • 京存助力自动驾驶,打造智能出行未来
  • 使用git页面如何用旧项目创建一个新项目出来并且保留所有分支内容和提交历史
  • GC1277替代OCH477/灿瑞芯片在电脑散热风扇中的应用