Linux:linux系统中目录的遍历

Linux系统中目录的遍历

1、Linux中目录的遍历

(1)函数opendir

打开需要被遍历的目录

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

(2)函数readdir

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

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

(3)函数closedir

关闭opendir打开的dir目录

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

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

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

cpp 复制代码
#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;
}
相关推荐
Yana.nice27 分钟前
Weblogic日志体系
linux
阿拉斯攀登39 分钟前
内核模块开发:module_init 与模块机制详解
linux·网络·嵌入式硬件·linux驱动
阿拉斯攀登1 小时前
字符设备驱动:file_operations 与读写实现
linux·嵌入式·linux驱动·字符设备驱动
阿拉斯攀登2 小时前
嵌入式 Linux 驱动概述:分类、内核模块、开发环境
linux·嵌入式硬件·linux内核·嵌入式·linux驱动
Uncertainty!!12 小时前
Ubuntu 22.04 安装超好用中文输入法rime-ice(雾凇拼音)过程记录
linux·ubuntu·中文输入法
ShineWinsu13 小时前
对于Linux:网络基础的解析
linux·网络·面试·udp·笔试·ip·tcp
↘"LYong14 小时前
旧版 CentOS 安装 Docker 完整指南(附国内镜像加速)
linux·运维·docker
Zhang~Ling15 小时前
Vim 多模式详解:命令、插入、底行与插件配置
linux·编辑器·vim
想你依然心痛16 小时前
Linux用户空间与内核空间通信:netlink、ioctl、mmap 零拷贝与性能对比
linux·运维·服务器
做个文艺程序员17 小时前
Linux第12篇:性能监控与瓶颈分析——CPU/内存/IO/网络全维度
linux·运维·网络