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;
}
相关推荐
l1x1n021 分钟前
Vim 编辑器常用操作详解(新手快速上手指南)
linux·编辑器·vim
ajassi20002 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
o不ok!2 小时前
Linux面试问题-软件测试
linux·运维·服务器
DaxiaLeeSuper2 小时前
Prometheus+Grafana+node_exporter监控linux服务器资源的方案
linux·grafana·prometheus
尽兴-3 小时前
如何将多个.sql文件合并成一个:Windows和Linux/Mac详细指南
linux·数据库·windows·sql·macos
kfepiza3 小时前
Netplan 中 bridges、bonds、ethernets、vlans 之间的关系 笔记250711
linux·tcp/ip·shell
小小不董4 小时前
深入理解oracle ADG和RAC
linux·服务器·数据库·oracle·dba
杰夫贾维斯5 小时前
CentOS Linux 8 的系统部署 Qwen2.5-7B -Instruct-AWQ
linux·运维·人工智能·机器学习·centos
kfepiza5 小时前
Netplan 配置网桥(Bridge)的模板笔记250711
linux·tcp/ip·ubuntu
kfepiza6 小时前
用Netplan配置网桥bridge笔记250711
linux·ubuntu·debian