LINUX编程学习笔记(十三) 遍历目录的两种方法

1 默认情况下  实际用户和有效用户是一样的

  实际用户:执行用户
  有效用户:权限用户
getuid()  实际用户
geteuid() 有效用户
chmod u+s 之后 ,其他人执行文件时,实际用户和有效用户会不一样


2 目录相关函数

int chdir(const char *path);改变当前目录
int mkdir(const char *pathname, mode_t mode); 创建目录
int rmdir(const char *pathname); 删除目录
 int unlink(const char *pathname); 删除文件
mode_t umask(mode_t mask); 设置文件权限屏蔽位
stat  fstat lstat文件目录状态

3 目录的遍历

3.1 方法一 opendir + readdir
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);



           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 */
           };

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>//exit()


int main()
{
	DIR *d = opendir("/home/zhao");
	if(d == 0)
	{
		perror("opendir:%m\n");
		exit(1);
	}
	
	struct dirent * de;
	while(de=readdir(d))
	{
		printf("%s \t%d\n",de->d_name,de->d_type);
	}
	//d_type 4 表示目录 8表示文件
	
	closedir(d);


	
}



3.2   方法2 scandir
   int scandir(const char *dirp, //目录名 
struct dirent ***namelist, //返回目录列表
int (*filter)(const struct dirent *), //回调函数 过滤目录 NULL表不过滤
int (*compar)(const struct dirent **, const struct dirent **)); //对查询结果排序 NULL表不排序


      过滤规则 filter返回0 则不过滤掉 非0则显示
排序规则 compar  >0 排在前面 <0排在后面
已有的排序
int alphasort(const void *a, const void *b);
int versionsort(const void *a, const void *b);


返回值: >=0 目录个数
-1 目录查找失败

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>//exit()


int filter(const struct dirent *);
int sort(const struct dirent**,const struct dirent **);


int main()
{
	struct dirent **d;
	//int r = scandir("/home/zhao",&d,filter,alphasort); 
	int r = scandir("/home/zhao",&d,filter,sort); //与alphasort你序
	printf("子目录个数为%d\n",r);
	while(*d != 0)
	{
		printf("%s\n",(*d)->d_name);	
		d++;
	}
	
	return 0;
}


//过滤掉名字以.开头的文件夹
int filter(const struct dirent* d)
{
	if(strncmp(d->d_name,".",1) == 0)
	{
		return  0;
	}
	
	return 1;
}




int sort(const struct dirent**a,const struct dirent **b)
{
	return -alphasort(a,b);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值