博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux编程学习笔记(十二) 遍历目录
阅读量:4589 次
发布时间:2019-06-09

本文共 2173 字,大约阅读时间需要 7 分钟。

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 
#include
#include
#include
//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   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 
#include
#include
#include
//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);}

转载于:https://www.cnblogs.com/snake-hand/archive/2013/06/12/3132867.html

你可能感兴趣的文章
workspace 配置
查看>>
C# 针对特定的条件进行锁操作,不用lock,而是mutex
查看>>
Spring归纳
查看>>
MyEclipse Web Project导入Eclipse Dynamic Web Project,无法部署到tomcat问 题
查看>>
24小时学通Linux内核之向内核添加代码
查看>>
python 函数
查看>>
Solr4.0 如何配置使用UUID自动生成id值
查看>>
Marketing™Series用户手册(Marketing™Series Manual)
查看>>
Java动态代理
查看>>
二维码开源库zbar、zxing使用心得
查看>>
框架设计读书笔记--扩展点设计--组合法
查看>>
Web开发小贴士 -- 全面了解Cookie
查看>>
收藏Javascript中常用的55个经典技巧
查看>>
Arm-linux-gcc-4.3.2安装步骤
查看>>
Java多线程与并发编程学习
查看>>
Support Vector Machine
查看>>
牛客-2018多校算法第五场C-KMP
查看>>
Linux查看文件内容
查看>>
[转]社会生活中十二大著名法则 1 马太效应 2 手表定理 3 不值得定律 4 彼得原理 5 零和游戏原理 6 华盛顿合作规律 7 酒与污水定律 8 水桶定律 9 蘑菇管理 10 奥...
查看>>
浅谈三层与实体
查看>>