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;
}
相关推荐
历程里程碑11 分钟前
Linux 17 程序地址空间
linux·运维·服务器·开发语言·数据结构·笔记·排序算法
CC.GG25 分钟前
【Linux】进程控制(二)----进程程序替换、编写自主Shell命令行解释器(简易版)
linux·服务器·数据库
H Journey1 小时前
Linux 下添加用户相关
linux·运维·服务器·添加用户
Trouvaille ~1 小时前
【Linux】线程同步与互斥(三):生产者消费者模型实战
linux·运维·c++·信号量·阻塞队列·生产者消费者模型·环形队列
遇见火星1 小时前
Linux Screen 命令入门指南
linux·运维·服务器
Doro再努力2 小时前
【Linux操作系统06】深入理解权限掩码与粘滞位
linux·运维·服务器
wdfk_prog2 小时前
[Linux]学习笔记系列 -- [drivers][dma]stm32-dma
linux·笔记·学习
mzhan0172 小时前
[Linux] vdso 32bit vs 64bit
linux·运维·服务器
旖旎夜光2 小时前
Linux(13)(上)
linux·网络
忧郁的橙子.2 小时前
26期_01_Pyhton linux基本命令
linux·运维·服务器