Linux:linux中目录的遍历和C中目录的遍历

1、Linux中目录的遍历

(1)函数opendir

打开需要被遍历的目录

DIR *opendir(const char *pathname);
  • pathname:待遍历的目录
  • return:成功则返回目录结构体指针,失败返回NULL

(2)函数readdir

依次读取目录结构体中的数据

dirent *readdir(DIR *dir);
  • dir:opendir返回的结构体指针
  • return:成功则返回当前目录下文件或文件夹的结构体,失败则返回NULL

(3)函数closedir

关闭opendir打开的dir目录

int closedir(DIR *dir);
  • dir:opendir返回的目录指针
  • return:成功返回0,失败返回-1

(4)遍历指定目录的所有文件和子目录

以下函数可以直接使用,目录下的所有子目录和文件都会被写入到txt文件中:

#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、C中目录的遍历

(1)What()

(2)Why()

(3)How()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值