日期:2014-05-16  浏览次数:20828 次

有关unix下目录流DIR的问题
请问有有关目录流DIR这种类型的资料吗?我不知道他究竟是什么结构,具体应该怎么用?谢谢

------解决方案--------------------
相关函数:open,opendir,closedir,rewinddir,seekdir,telldir,scandir
表头文件:#include <sys/types.h>
#include <dirent.h>
定义函数: struct dirent *readdir(DIR *dir)
函数说明: readdir()返回参数dir目录流的下个目录进入点。结构dirent定义如下:
struct dirent
{
ino_t d_ino;
ff_t d_off;
signed short int d_reclem;
unsigned char d_type;
char d_name[256];
}

d_ino 此目录进入点的inode
d_off 目录文件开头到此目录进入点的位移
d_reclen _name的长度,不包含NULL字符
d_type d_name所指的文件类型
d_name 文件名

返回值:成功则返回下个目录进入点。有错误发生或读取到目录文件尾则返回NULL
附加说明: EBADF参数dir为无效的目录流

范例:
/* 读取/etc/rc.d目录文件结构,然后显示该目录下的文件 */

#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

main()
{
DIR *dir;
struct dirent *ptr;
int i;

dir=opendir( "/etc/rc.d ");
while((ptr=readdir(dir)) != NULL)
{
printf( "d_name: %s\n ", ptr-> d_name);
}
closedir(dir);
}

------解决方案--------------------
在glibc的源码里定义了(针对unix体系):
struct __dirstream
{
int fd; /* File descriptor. */

char *data; /* Directory block. */
size_t allocation; /* Space allocated for the block. */
size_t size; /* Total valid data in the block. */
size_t offset; /* Current offset into the block. */

off_t filepos; /* Position of next entry to read. */

__libc_lock_define (, lock) /* Mutex lock for this structure. */
};

DIR类型对用户来讲是不可见的,因为对于不同系统其结构有可能不一样。
之所以没有实际的定义编译还可以通过,那就不太清楚了。
------解决方案--------------------
去下一个glibc的原代码,dirstream.h中有这个结构的定义:

struct __dirstream
{
int fd; /* File descriptor. */

char *data; /* Directory block. */
size_t allocation; /* Space allocated for the block. */
size_t size; /* Total valid data in the block. */
size_t offset; /* Current offset into the block. */

off_t filepos; /* Position of next entry to read. */

__libc_lock_define (, lock) /* Mutex lock for this structure. */
};