typedef struct __dirstream DIR;
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. */
};
1. opendir()
typedef struct __dirstream DIR;
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. */
};
头文件
#include<sys/types.h>
#include<dirent.h>
函数原型
DIR* opendir (const char * path ); (获取path子目录下的所由文件和目录的列表,如果path是个文件则返回值为NULL)
功能
打开一个目录,在失败的时候返回一个空的指针。
返回值(DIR)
DIR 结构体的原型为:struct_dirstream
在linux系统中:
2.readdir
头文件
#include<dirent.h>
函数原型
struct dirent* readdir(DIR* dir_handle); (个人理解循环读取dir_handle,目录和文件都读)
功能
读取opendir 返回值的那个列表
返回值
返回dirent结构体指针,dirent结构体成员如下,(文件和目录都行)
struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}
3.用例
代码
#include<stdio.h>
#include<dirent.h>
int main(void)
{
DIR *dirptr=NULL;
int i=1;
struct dirent *entry;
if((dirptr = opendir("test.dir"))==NULL)
{
printf("opendir failed!");
return 1;
}
else
{
while(entry=readdir(dirptr))
{
printf("filename%d=%s\n",i,entry->d_name);
i++;
}
closedir(dirptr);
}
return 0;
}
输出:
filename1=dir1
filename2=file3
filename3=..
filename4=dir3
filename5=.
filename6=file1
filename7=file2
filename8=dir2