目录项dirent详解及示例

dirent结构体

struct dirent {
	ino_t	d_ino;       		/* inode number*/
    off_t   d_off;      		/* offset to the next dirent */
    unsigned short d_reclen;    /* length of this record 本条记录的长度*/
    unsigned char  d_type;      /* type of file; not supported by all file system types */
    char    d_name[256];		/* filename */
 };

dirent.h中的常用的三个函数

#include <dirent.h>
DIR *opendir(const char *dirname);	//根据路径,打开一个目录文件,DIR是一个结构体,类似于FILE,不需要去深究其内部,只需要得到它就行
DIR *fdopendir(int fd);			    //这个是根据文件描述符fd来打开一个目录文件

struct dirent *readdir(DIR *dirp);	//从目录文件中获取所有dirent,调用一次只可以获取到一个dirent结构体,多次获取,直到该函数返回NULL时表示已经获取完了

int closedir(DIR *dirp);			//用完之后关闭

示例代码


#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
 
void printdir(char *dir, int depth)		//传进来一个路径
{
	DIR *dp;
	struct dirent *entry;				//声明一个dirent指针,用来接收readdir返回来的值
	struct stat statbuf;				//stat是看文件信息的结构体
 
	if ((dp = opendir(dir)) == NULL) {	//首先打开一个目录
		fprintf(stderr, "Can`t open directory %s\n", dir);
		return ;
	}
	
	chdir(dir);							//进入这个目录,主要是lstat需要在当前目录下使用,否则就要给其一个绝对路径
										//snprintf打印一个绝对路径太麻烦,这里直接进到这个目录里,使用lstat
	while ((entry = readdir(dp)) != NULL) {	//当为NULL的时候就代表已经遍历完该目录下的所有文件(目录也是一个文件)了
		lstat(entry->d_name, &statbuf);		//lstat可以得到软链接文件的属性
		if (S_ISDIR(statbuf.st_mode)) {		//判断是否为目录
			if (strcmp(entry->d_name, ".") == 0 || 		//不打印 . 和 .. 两个目录
				strcmp(entry->d_name, "..") == 0 )  
				continue;	
			printf("%*s%s/\n", depth, "", entry->d_name);	
			printdir(entry->d_name, depth+4);			//打印该目录下的所有目录,递归打印,depth其实就是一个缩进
		} else
			printf("%*s%s\n", depth, "", entry->d_name);	//如果不是一个目录,就直接打印
	}
	chdir("..");
	closedir(dp);	
}
 
 
int main(int argc, char *argv[])
{
	char *topdir = ".";
	if (argc >= 2)
		topdir = argv[1];
 
	printf("Directory scan of %s\n", topdir);
	printdir(topdir, 0);
	printf("done.\n");
	exit(0);
}
  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值