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
");
		exit(1);
	}
	
	struct dirent * de;
	while(de=readdir(d))
	{
		printf("%s 	%d
",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
",r);
	while(*d != 0)
	{
		printf("%s
",(*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);
}



原文地址:https://www.cnblogs.com/snake-hand/p/3144848.html