Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1736275
  • 博文数量: 438
  • 博客积分: 9799
  • 博客等级: 中将
  • 技术积分: 6092
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-25 17:25
文章分类

全部博文(438)

文章存档

2019年(1)

2013年(8)

2012年(429)

分类: 系统运维

2012-03-28 14:01:48

目录可以被任何有这个目录读权限的人读。然而只有内核才能写一个目录,来保证文件系统的健全。回想4.5节目录的写权限位和执行权限位决定我们是否可以在该目录创建和删除文件--他们并没有指定我们是否可以写这个目录本身。


目录的真实格式取决于UNIS系统实现和文件系统的设计。早期系统,比如Version 7,有一个简单的结构:每个目录项有16字节,其中14字节为文件名,而2个字节为i-node号。当更长的文件名被加入到4.2BSD时,每个项变为可 变长度,这意味着任何读目录的程序都依赖于系统。为了简化这个,一堆目录指令被发展起来,并成为POSIX.1的部分。许多系统避免程序使用read函数 来访问目录的内容,因此更加隔离了程序和目录格式的实现相关的细节。



  1. #include <dirent.h>

  2. DIR *opendir(const char *pathname);
  3. 成功返回指针,失败返回null。

  4. struct dirent *readdir(DIR *dp);
  5. 成功返回指针,目录尾或失败返回null。

  6. void rewinddir(DIR *dp);
  7. int closedir(DIR *dp);
  8. 成功返回0,失败返回-1。

  9. long telldir(DIR *dp);
  10. 返回dp相关的目录的当前位置。

  11. void seekdir(DIR *dp, long loc);

telldir和seekdir函数不是基本POSIX.1标准的一部分,它们是SUS的XSI扩展,所以所有遵守协议的UNIX系统实现都被期望来提供它们。

看下面的代码,ls的简单实现:



  1. #include <dirent.h>
  2. #include <unistd.h>

  3. int
  4. main(int argc, char *argv[])
  5. {
  6.     DIR *dp;
  7.     struct dirent *dirp;

  8.     if (argc != 2)
  9.         exit(1);

  10.     if ((dp = opendir(argv[1])) == NULL)
  11.         exit(1);
  12.     while ((dirp = readdir(dp)) != NULL)
  13.         printf("%s\n", dirp->d_name);
  14.     closedir(dp);
  15.     exit(0);
  16. }


在文件里定义的dirent结构体依赖于系统实现。实现定义这个结构体至少要包括以下两个成员:
struct dirent {
  ino_t d_ino;    /* i-node号 */
  char d_name[NAME_MAX + 1]; /* null结尾的文件名 */
};

d_ino项不在POSIX.1中定义,因为它是一个实现特性,但它定义在POSIX.1的XSI扩展中。POSIX.1只在这个结构体里定义了d_name项。


注意NAME_MAX在Solaris上不是一个定义好的常量--它的值取决于目录所在的文件系统,而且它的值通常是从fpathconf函数得到。 NAME_MAX的一个普遍的值是255。(回想下第2节关于限量的表。)尽管如此,既然文件名是null终止的,数组d_name在头文件里怎么定义并 不重要,因为数据尺寸并不表明文件名的长度。


DIR结构体是一个内部结构,被那六个函数用来维护关于被读目录的信息。DIR结构体的作用与标准I/O库维护的FILE结构体类似,我们会在第5章讲述。


从opendir返回的DIR结构体的指针被其它5个函数使用。opendir函数初始化所有事情,以便第一个readdir操作读到目录的第一项。在目录里的项的顺序是实现相关的,而且通常不是字母序。


我们将使用这些目录函数来写一个遍历文件层次的程序。目标是产生各种类型的文件的计数,就如4.3节末的表一样。程序接受一个参数--开始的路径名--并 从那一点开始递归地遍历层次结构。Solaris提供了一个函数,ftw,来进行层次结构的真正遍历,并为每个文件调用用户定义的函数。


这个函数的问题是 它为每个文件调用stat函数,这会导致程序去解析符号链接。例如,如果我们从根目录开始,并有一个指向/usr/lib的名为/lib的符号链接, /usr/lib目录里的所有文件都会被计数两次。为了更正它,Solaris提供了一个额外的函数,nftw,带有一个阻止解析符号链接的可选项。尽管 我们可以使用ntfw,但我们仍将写我们自己的简单的文件遍历器来展示目录函数的用法。


在SUS,ftw和nftw都包含在基本POSIX.1规范的XSI扩展中。Solaris 9和Linux 2.4.22包含了实现。基于BSD的系统有一个不同的函数,fts,提供了相似的功能。它在FreeBSD 5.2.1、Mac OS X 10.3和Linux 2.4.22中可用。


看下面的代码:



  1. #include <dirent.h>
  2. #include <limits.h>
  3. #include <sys/stat.h>
  4. #include <unistd.h>
  5. #include <errno.h>

  6. /* function type that is called for each filename */
  7. typedef int Myfunc(const char *, const struct stat *, int);

  8. static Myfunc myfunc;
  9. static int myftw(char *, Myfunc *);
  10. static int dopath(Myfunc *);
  11. char *path_alloc(int *sizep); /* from section 2.5.5 */

  12. static long nreg, ndir, nblk, nchr, nfifo, nslink, nsock, ntot;

  13. int
  14. main(int argc, char *argv[])
  15. {
  16.     int ret;

  17.     if (argc != 2)
  18.         exit(1);

  19.     ret = myftw(argv[1], myfunc); /* does it all */

  20.     ntot = nreg + ndir + nblk + nchr + nfifo + nslink + nsock;
  21.     if (ntot == 0)
  22.         ntot = 1; /* avoid divide by 0; print 0 for all counts */
  23.     printf("regular files = %71d, %5.2f %%\n", nreg, nreg*100.0/ntot);
  24.     printf("directories = %71d, %5.2f %%\n", ndir, ndir*100.0/ntot);
  25.     printf("block special = %71d, %5.2f %%\n", nblk, nblk*100.0/ntot);
  26.     printf("char special = %71d, %5.2f %%\n", nchr, nchr*100.0/ntot);
  27.     printf("FIFOs = %71d, %5.2f %%\n", nfifo, nfifo*100.0/ntot);
  28.     printf("symbolic links = %71d, %5.2f %%\n", nslink, nslink*100.0/ntot);
  29.     printf("sockets = %71d, %5.2f %%\n", nsock, nsock*100.0/ntot);

  30.     exit(ret);
  31. }

  32. /*
  33.  * Descend through the hierarchy, starting at "pathname".
  34.  * The caller's func() is called for every file.
  35.  */
  36. #define FTW_F 1 /* file other than directory */
  37. #define FTW_D 2 /* directory */
  38. #define FTW_DNR 3 /* directory that can't be read */
  39. #define FTW_NS 4 /* file that we can't stat */

  40. static char *fullpath; /*contains full pathname for every file */

  41. static int /* we return whatever func() returns */
  42. myftw(char *pathname, Myfunc *func)
  43. {
  44.     int len;
  45.     fullpath = path_alloc(&len); /* malloc's for PATH_MAX+1 bytes */
  46.     strncpy(fullpath, pathname, len); /* protect against */
  47.     fullpath[len -1] = 0; /* buffer overrun */

  48.     return(dopath(func));
  49. }

  50. /*
  51.  * Descend through the hierarchy, starting at "fullpath".
  52.  * If "fullpath" is anything other than a directory, we lstat() it,
  53.  * call func(), and return. For a directory, we call ourself
  54.  * recursively for each name in the directory.
  55.  */
  56. static int /* we return whatever func() returns */
  57. dopath(Myfunc* func)
  58. {
  59.     struct stat statbuf;
  60.     struct dirent *dirp;
  61.     DIR *dp;
  62.     int ret;
  63.     char *ptr;

  64.     if (lstat(fullpath, &statbuf) < 0) /* stat error */
  65.         return(func(fullpath, &statbuf, FTW_NS));
  66.     if (S_ISDIR(statbuf.st_mode) == 0) /* not a directory */
  67.         return(func(fullpath, &statbuf, FTW_F));

  68.     /*
  69.      * It's a directory. First call func() for the directory,
  70.      * then process each filename in the directory.
  71.      */
  72.     if ((ret = func(fullpath, &statbuf, FTW_D)) != 0)
  73.         return(ret);

  74.     ptr = fullpath + strlen(fullpath); /*point to end of fullpath */
  75.     *ptr++ = '/';
  76.     *ptr = 0;

  77.     if ((dp = opendir(fullpath)) == NULL) /* can't read directory */
  78.         return(func(fullpath, &statbuf, FTW_DNR));

  79.     while ((dirp = readdir(dp)) != NULL) {
  80.         if (strcmp(dirp->d_name, ".") == 0 ||
  81.             strcmp(dirp->d_name, "..") == 0)
  82.                 continue; /*ignore dot and dot-dot */
  83.     
  84.         strcpy(ptr, dirp->d_name); /* append name after slash */
  85.     
  86.         if ((ret = dopath(func)) != 0)
  87.             break; /* time to leave */
  88.     }
  89.     ptr[-1] = 0; /* erase everything from slash onwards */
  90.     
  91.     if (closedir(dp) < 0) {
  92.         printf("can't close directory %s", fullpath);
  93.         return -1;
  94.     }

  95.     return ret;
  96. }

  97. static int
  98. myfunc(const char *pathname, const struct stat *statptr, int type)
  99. {
  100.     switch (type) {
  101.     case FTW_F:
  102.         switch (statptr->st_mode & S_IFMT) {
  103.         case S_IFREG: nreg++; break;
  104.         case S_IFBLK: nblk++; break;
  105.         case S_IFCHR: nchr++; break;
  106.         case S_IFIFO: nfifo++;break;
  107.         case S_IFLNK: nslink++; break;
  108.         case S_IFSOCK: nsock++; break;
  109.         case S_IFDIR:
  110.             printf("for S_IFDIR for %s", pathname);
  111.                 /* directories should have type = FTW_D */
  112.         }
  113.     break;

  114.     case FTW_D:
  115.         ndir++;
  116.         break;

  117.     case FTW_DNR:
  118.         printf("can't read directory %s", pathname);
  119.         break;
  120.     
  121.     case FTW_NS:
  122.         printf("stat error for %s", pathname);
  123.         break;
  124.     
  125.     default:
  126.         printf("unknown type %d for pathname %s", type, pathname);
  127.     }
  128.     return(0);
  129. }

  130. #ifdef PATH_MAX
  131. static int pathmax = PATH_MAX;
  132. #else
  133. static int pathmax = 0;
  134. #endif

  135. #define SUSV3 200112L

  136. static long posix_version = 0;

  137. /* If MATH_MAX is indeterminate, no guarantee this is adquate */
  138. #define PATH_MAX_GUESS 1024

  139. char *
  140. path_alloc(int *sizep) /* also return allocated size, if nonnull */
  141. {
  142.     char *ptr;
  143.     int size;

  144.     if (posix_version == 0)
  145.         posix_version = sysconf(_SC_VERSION);

  146.     if (pathmax == 0) { /*first time through */
  147.         errno = 0;
  148.         if ((pathmax = pathconf("/", _PC_PATH_MAX)) < 0) {
  149.             if (errno == 0)
  150.                 pathmax = PATH_MAX_GUESS; /* it's indeterminate */
  151.             else
  152.                 printf("pathconf error for _PC_PATH_MAX\n");
  153.         } else {
  154.             pathmax++; /* add one since it's relative to root */
  155.         }
  156.     }
  157.     if (posix_version < SUSV3)
  158.         size = pathmax + 1;
  159.     else
  160.         size = pathmax;

  161.     if ((ptr = malloc(size)) == NULL)
  162.         printf("malloc error for pathname\n");

  163.     if (sizep != NULL)
  164.         *sizep = size;
  165.     return(ptr);
  166. }


运行./a.out /dev,结果为:
regular files  =   283, 32.49 %
directories    =   75,  8.61 %
block special  = 29,  3.33 %
char special   =  196, 22.50 %
FIFOs          =      1,  0.11 %
symbolic links = 285, 32.72 %
sockets        =    2,  0.23 %

更多关于遍历文件系统和许多标准UNIX系统命令(find、ls、tar等)里这种技术的使用,参考Fowler, Korn, and Vo[1989]。

阅读(1126) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~