曲径通幽论坛

标题: readdir [打印本页]

作者: beyes    时间: 2009-2-12 22:34
标题: readdir
在一个目录流 dirp 中, readdir 函数返回一个指向描述下一个目录条目的结的指针.连续调用 readdir则返回更多的目录条目.若错误和到了目录末尾,readdir就会返回 NULL.在 POSIX 兼容系统(POSIX-compliant)里,如果是因为在目录末尾而返回 NULL的系统不会改变 errno的值,但如果是因为错误而返回 NULL的,就会设置 errno .

用法:
#include <sys/types.h>
#include <dirent.h>
struct dirent *readdir(DIR *dirp);

注意,如果有其他的进程同时在创建和删除目录里的文件, readdir 扫描并不保证会列出所有在目录里的文件.

dirent 结构包含的目录条目细节包含下面的2个条目:

ino_t d_ino : 文件的节点
char d_name[] : 文件名

如果要确定更多的目录里文件的细节,需要使用 stat 调用来进行查询.

struct dirent
  {
#ifndef __USE_FILE_OFFSET64
    __ino_t d_ino;
    __off_t d_off;
#else
    __ino64_t d_ino;
    __off64_t d_off;
#endif
    unsigned short int d_reclen;
    unsigned char d_type;
    char d_name[256];           /* We must not include limits.h! */
  };
作者: beyes    时间: 2009-2-13 18:05
函数应用示例
01 #include <unistd.h>
02 #include <stdio.h>
03 #include <sys/types.h>
04 #include <dirent.h>
05
06 int main()
07 {
08         DIR *dp;
09         struct dirent *entry;
10
11         dp = opendir("/root/C");
12
13         while( (entry = readdir(dp)) != NULL )
14         printf("%s\\n",entry->d_name);
15
16         return 0;
17 }

分析:
11. 使用 opendir 函数打开 /root/C 目录并建立了目录流 DIR 的指针 dp

13. 使用 while 循环不断打印出目录流中的条目,每次应用 readdir 函数就会得到目录流中的下一个条目。
    readdir 函数返回一个指向目录中文件自身(也是目录流中的条目)相关信息的一个结构指针 entry 。

14. 打印目录条目--打印结果为
[root@localhost C]# ./readdir.exe
readdir.exe
fileno.c
write.exe
read.exe
printf_test.exe
write.c
LSEEK
printdir.exe
read.c
readdir.c
new-1
..
fileno.exe
printdir.c
COPY
.
printf_test.c

由上可见,目录里面的文件名字信息(包括子目录)都被打印出来了。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2