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;
}
相关推荐
Johny_Zhao3 小时前
Keepalived与Nginx架构选型
linux·nginx·信息安全·云计算·apache·shell·yum源·keepalive·系统运维
FlightYe5 小时前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频
by209996 小时前
Linux 文件描述符与重定向
linux·服务器
橙橙笔记6 小时前
Linux基础与命令的学习
linux·运维·服务器·shell
无奈笑天下6 小时前
银河麒麟桌面操作系统【命令行配置文件与图片搜索功能】操作方法
linux·运维·服务器
飞花漫卷,情随岁迁7 小时前
网络数据包转发与内核机制:小白概念科普
linux·运维·网络·数据库·mysql·oracle·智能路由器
.道阻且长.8 小时前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
学以智用9 小时前
CentOS 目录穿梭
linux
goehou10 小时前
改错一行 fstab,SSH 就再也连不上了
linux·运维·故障恢复·fstab
如夏倾城12 小时前
进程状态模型详解:从三态、五态到 Linux 状态码映射
java·linux·服务器