文件和目录之读目录
文件和目录之读目录
对某个目录具有访问权限的任一用户都可读该目录,但是,为了防止文件系统产生混乱,只有内核才能写目录。一个目录的写权限位和执行权限位决定了在该目录中能否创建新文件以及删除文件,它们并不表示能否写目录本身。
#include <dirent.h>*opendir( * dirent *readdir( DIR * rewinddir( DIR * closedir( DIR *-
telldir( DIR * seekdir( DIR *dp, loc );
头文件<dirent.h>中定义的dirent结构与实现有关。几种典型的UNIX实现对此结构所作的定义至少包含下列两个成员:
d_name[NAME_MAX + ];
DIR结构是一个内部结构,上述6个函数用这个内部结构保存当前正被读的目录的有关信息。其作用类似与FILE结构。FILE结构由标准I/O库维护。
由opendir返回的指向DIR结构的指针由另外5个函数使用。opendir执行初始化操作,使第一个readdir读目录中的第一个目录项。目录中各目录项的顺序与实现有关。它们通常并不按字母顺序排序。
程序清单4-7 递归降序遍历目录层次结构,并按文件类型计数
[root@localhost apue]# cat -b prog4- #include
#include <dirent.h>
#include <limits.h>
#include <errno.h>
pathmax =
pathmax =
SUSV3 200112L
posix_version =
PATH_MAX_GUESS 1024
*
path_alloc( *sizep)
* (posix_version == posix_version =
(pathmax == ) {
errno = ((pathmax = pathconf(, _PC_PATH_MAX)) < (errno == pathmax = PATH_MAX_GUESS;
err_sys( } pathmax++;
(posix_version < size = pathmax +
size =
((ptr = malloc(size)) == err_sys( (sizep != *sizep =
typedef Myfunc( *, stat *, myftw( *, Myfunc * dopath( Myfunc *
main( argc, *
( argc != err_quit(
ret = myftw( argv[], myfunc );
ntot = nreg + ndir + nblk + nchr + nfifo + nslink + ( ntot == ntot = ;
printf( , nreg, nreg*/ printf( , ndir, ndir*/ printf( , nblk, nblk*/ printf( , nchr, nchr*/ printf( , nfifo, nfifo*/ printf( , nslink, nslink*/ printf( , nsock, nsock*/
FTW_F 1 /* file other than directory */