关于目录文件的分析
/lib/src/vim
/,lib,src,都是目录文件,而vim是普通文件 -------------------opendir() 返回一个DIR *--------->readdir(DIR *) 返回一个dirent 结构的指针
struct dirent
{
}
struct __dirstream
{
void *__fd; /* `struct hurd_fd' pointer for descriptor. */
char *__data; /* Directory block. */
int __entry_data; /* Entry number `__data' corresponds to. */
char *__ptr; /* Current pointer into the block. */
int __entry_ptr; /* Entry number `__ptr' corresponds to. */
size_t __allocation; /* Space allocated for the block. */
size_t __size; /* Total valid data in the block. */
__libc_lock_define (, __lock) /* Mutex lock for this structure. */
};
typedef struct __dirstream DIR;
例子程序:
/*****************************
* 递归遍历一个目录下的所有文件和目录
* author:wuyichao
* date:2011-5-8
******************************/
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
static char fullpath[128]; //每个文件的文件名
static int dopath()
{
struct stat statbuf;
struct dirent *dirp;
DIR *dp;
char *ptr;
int ret; //返回状态
//如果是普通文件就打印出来
if (lstat(fullpath, &statbuf) < 0) {
printf("lstat error\n");
exit(1);
}
if (S_ISDIR(statbuf.st_mode) == 0) {//not a directory
//打印文件
printf("---%s\n",fullpath);
return 1;//结束一次遍历,叶子节点
} else {
//打印目录
printf("d--%s\n", fullpath);
ptr = fullpath + strlen(fullpath);
*ptr++ = '/';
*ptr = 0;
//打开目录
if ((dp = opendir(fullpath)) == NULL) {//can't read directory
printf("opendir error\n");
exit(2);
}
while ((dirp = readdir(dp)) != NULL) {
if (strcmp(dirp->d_name, ".") == 0 ||
strcmp(dirp->d_name, "..") == 0)
continue;
strcpy(ptr, dirp->d_name); //添到旧文件名后--->新的目录名
dopath(ptr);//recursive
}
return 1;
}
//如果是目录,就递归
}
int
main(int argc, char *argv[])
{
if (argc != 2) {
printf("usage: ftw <starting-pathname>");
exit(3);
}
strcpy(fullpath, argv[1]);
dopath();
return 0;
}
参考书籍:unix高级环境编程(richard stevens)