linux下遍历目录和文件

目录操作相关函数

1、opendir 打开目录

DIR *opendir(const char *name);

参数:要打开的目录名

返回值:指向目录的指针

这里的DIR类型可以int dirfd(DIR *dirp)函数 转变为描述符 fd

2、读目录 readdir;

struct dirent *readdir(DIR *dirp);

参数:opendir的返回值   

返回值:目录项结构体

这里的读目录的意思就是把目录的详细信息包括文件名,文件类型等存到结构体 dirent中返回,struct dirent的详细内容是:

struct dirent
{
     ino_t d_ino;                //此目录进入点的inode
     ff_t d_off;                 //此目录文件开头至此目录进入点的位移
     signed short int d_reclen;  //d_name 的长度,不包含NULL字符
     unsigned char d_type;       //d_name所指的文件类型
     har d_name[256];            //文件名
};

其中 重要的 d_type表示的是文件类型,总共有8种取值

DT_BLK     块设备

DT_CHR    字符设备

DT_DIR      目录

DY_LNK     软连接

DT_FIFO     管道

DT_REG     普通文件

DT_SOCK   套接字

DT_UNKNOWN 未知

3、closedir 关闭目录

int closedir(DIR *dirp);

 

下面程序统计目录包括子目录下文件的数量

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <dirent.h>

int get_filenum(char *pathname)
{
	int total = 0;
	DIR *dir = NULL;
	dir = opendir(pathname);
	if(dir == NULL)
	{
		perror("opendir error");
		exit(1);
	}
	//循环读目录中的文件
	struct dirent *ptr = NULL;
	while((ptr = readir(ptr)) != NULL)
	{
		if(strcmp(".", ptr->d_name) == 0 || strcmp("..",ptr->d_name) == 0)
		{
			continue;
		}
		//判断是不是普通文件
		if(ptr->d_type == DT_REG)
		{
			total++;
		}
		if(ptr->d_type == DT_DIR)
		{
			//求出子目录,递归
			char path[1024] = {0};
			sprintf(path,"%s/%s",root,ptr->d_name);
			total += get_filenum(path);
		}
	}

	close(dir);
	return total;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值