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;
}
相关推荐
zwtahql26 分钟前
ubuntu远程ssh连接
linux·ubuntu·ssh
南烟斋..28 分钟前
嵌入式系统(51单片机)核心外设详解:UART通信与DS18B20温度采集
linux·运维·网络
不染尘.29 分钟前
Linux的rpm与yum
linux·mysql·jdk·centos·tomcat·ssh
重生之绝世牛码39 分钟前
Linux软件安装 —— SSH免密登录
大数据·linux·运维·ssh·软件安装·免密登录
初听于你1 小时前
IP地址与路由器地址
linux·运维·服务器·网络·tcp/ip·计算机网络·智能路由器
FJW0208142 小时前
【Linux】SElinux的管理及优化
linux·运维·服务器
坐怀不乱杯魂2 小时前
Linux - 进程控制
linux·运维·服务器
重生之绝世牛码2 小时前
Linux软件安装 —— zookeeper集群安装
大数据·linux·运维·服务器·zookeeper·软件安装
额1292 小时前
磁盘物理卷、卷组、逻辑卷管理
linux·运维·服务器
Maggie_ssss_supp2 小时前
Linux-正则表达式
linux·运维·正则表达式