linux 下遍历目录树方法总结
linux 下遍历目录树方法总结
转自:
/anxuegang/article/details/6443737
几天需要实现对整个目录树的遍历,查阅了相关的一些资料。
开始找到的原始的方法是使用 readdir() 与 lstat() 函数实现递
归遍历,后来发现 linux 对于目录遍历这种最常用的操作已
经提供了很完善的接口: ftw() 与 nftw() 。下面就这两种方法
具体说明一下。 1、手动实现递归 1.1 stat() 函数族 stat 函数
族包括: stat,fstat 以及 lstat 函数, 都是向用户返回文件的属
性信息(元数据)
#include
int stat(const char*pathname,struct stat*buf);
int fstat(int filedes,struct stat*buf);
int lstat(const char *pathname,struct stat*buf);
三个函数的返回: 若成功为 0,出错为 -1。对一个
pathname ,
stat 函数返回一个与此命名文件有关的信息结构,
fstat 函数
获得已在描述符 filedes 上打开的文件的有关信息。
lstat 函
数类似于 stat, 但是当命名的文件是一个符号连接时,
lstat
返回该符号连接的有关信息,而不是由该符号连接引用的文
件的信息。
第二个参数是个指针,它指向一个我们应提
供的结构。这些函数填写由 buf 指向的结构。该结构的实际 定义可能所实施而有所不同,但其基本形式是:
struct stat{
mode st_mode; /* 文件类型和方式 ( 许可数 )*/ ino st_ino;/* i- 节点号 (序列号 )*/ dev st_dev;/* 设备号 (文件系统 )*/ dev st_rdev;/* 特殊文件的设备号 */ nlink st_nlink;/* 连接数 */ uid st_uid;/* 属主的用户 ID*/ gid st_gid;/* 属主的组 ID*/ off st_size;/* 普通文件的字节长度 */ time st_atime;/* 最后存取时间 */ time st_mtime;/* 最后修改存取时间 */ time st_ctime;/* 最后文件状态更改时间 */ long st_blksize;/* 最佳 I/O 块长 */ long st_blocks;/* 分配的 512 字节块块数
};下面是一个简单的测试 #include
#include
#include
int main(int argc, char **argv){
struct stat buf;
if(stat(argv[1],&buf)) {
printf("[stat]:error!/n");
return -1;
printf("st_dev:%d/n",buf.st_dev);
printf("st_ino:%d/n",buf.st_ino);
printf("st_mode:%d
S_ISDIR:%d/n",buf.st_mode,S_ISDIR(buf.st_mode));
printf("st_nlink:%d/n",buf.st_nlink);
printf("st_uid:%d/n",buf.st_uid);
printf("st_gid:%d/n",buf.st_gid);
printf("st_rdev:%d/n",buf.st_rdev);
printf("st_size:%d/n",buf.st_size);
printf("st_blksize:%lu/n",buf.st_blksize);
printf("st_blocks:%lu/n",buf.st_blocks);
printf("st_atime:%ld/n",buf.st_atime);
printf("st_mtime:%ld/n",buf.st_mtime);
printf("st_ctime:%ld/n",buf.st_ctime);
return 0;
} 这里补充说明一下 linux 中文件的基本类型。 1. 普通文件
(Regular file) 。这是最常见的文件类型,这种文件包含了某
种形式的数据。至于这种数据是文本还是二进制数据对于系 统核而言并无区别。对普通文件内容的解释由处理该文件的 应用程序进行。
2. 目录文件 (Directory file) 。这种文件包含了其