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;
}
相关推荐
難釋懷2 分钟前
Shell脚本-while循环语法结构
linux·运维·服务器·bash
B64A-消闲19 分钟前
shell命令一
linux·运维
biter008821 分钟前
ubuntu(28):ubuntu系统多版本conda和多版本cuda共存
linux·人工智能·ubuntu·conda
兜小糖的小秃毛27 分钟前
两段文本比对,高亮出差异部分
linux·前端·javascript
电鱼智能的电小鱼41 分钟前
基于 EFISH-SBC-RK3588 的无人机通信云端数据处理模块方案‌
linux·网络·人工智能·嵌入式硬件·无人机·边缘计算
星霜旅人1 小时前
【Linux】Vim文本编辑器
linux
難釋懷1 小时前
Shell脚本-for循环应用案例
linux·运维·服务器·bash
昊昊昊昊昊明2 小时前
10天学会嵌入式技术之51单片机-day-7
linux·运维·网络
达斯维达的大眼睛2 小时前
如何在Linux用libevent写一个聊天服务器
linux·运维·服务器·网络
末央&2 小时前
【Linux】gdb工具,Linux 下程序调试的 “透视眼”
linux·运维·服务器