首页 > 代码库 > Linux--基础篇--DIR dirent stat
Linux--基础篇--DIR dirent stat
Linux下 DIR结构体定义为
1 struct __dirstream 2 { 3 void *__fd; 4 char *__data; 5 int __entry_data; 6 char *__ptr; 7 int __entry_ptr; 8 size_t __allocation; 9 size_t __size;10 __libc_lock_define (, __lock)11 };12 typedef struct __dirstream DIR;
该结构体保存目录相关的信息,比如opendir(const char *);返回的就是DIR * 的类型;
用到该结构体的函数还有:
1 struct dirent *readdir(DIR *dp);2 void rewinddir(DIR *dp);3 int closedir(DIR *dp);4 long telldir(DIR *dp);5 void seekdir(DIR *dp,long loc);
得到DIR * 后,传给readdir(DIR *)函数 就可以得到dirent类型的指针 dirent结构体不仅保存了目录信息,还保存了某个文件的具体信息
dirent 结构体定义为
1 struct dirent2 {3 long d_ino; /* inode number 索引节点号 */4 off_t d_off; /* offset to this dirent 在目录文件中的偏移 */5 unsigned short d_reclen; /* length of this d_name 文件名长 */6 unsigned char d_type; /* the type of d_name 文件类型 */7 char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */8 }
通过dirent 的d_name 借助下面这个函数
int stat(const char *file_name, struct stat *buf);
可以得到某个文件更详细的信息;也就可以实现linux中ls的功能了
stat结构体的定义为
1 struct stat { 2 mode_t st_mode; //文件访问权限 3 ino_t st_ino; //索引节点号 4 dev_t st_dev; //文件使用的设备号 5 dev_t st_rdev; //设备文件的设备号 6 nlink_t st_nlink; //文件的硬连接数 7 uid_t st_uid; //所有者用户识别号 8 gid_t st_gid; //组识别号 9 off_t st_size; //以字节为单位的文件容量10 time_t st_atime; //最后一次访问该文件的时间11 time_t st_mtime; //最后一次修改该文件的时间12 time_t st_ctime; //最后一次改变该文件状态的时间13 blksize_t st_blksize; //包含该文件的磁盘块的大小14 blkcnt_t st_blocks; //该文件所占的磁盘块15 };
这里给出一个ls的简单实现(查考UNIX 环境高级编程):
查考:http://www.liweifan.com/2012/05/13/linux-system-function-files-operation/
Linux--基础篇--DIR dirent stat
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。