一.头文件
#include <dirent.h>
二.结构体
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! */ };
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. */ }; typedef struct __dirstream DIR;
三.API函数
int closedir(DIR *dirp);
关闭目录
DIR *opendir(const char *dirname);
打开目录
struct dirent *readdir(DIR *dirp);
读目录
void seekdir(DIR *dirp, long loc);
设置目录流目前的读取位置
long telldir(DIR *dirp);
目录流的当前位置
四.例子
#include <sys/types.h> #include <dirent.h> #include <stdio.h> int main(int argc, char *argv[]) { DIR *dp; struct dirent *dirp; if (argc != 2){ printf("use like ./ls /dev \n"); return 0; } if ((dp = opendir(argv[1])) == NULL){ printf("can not open dir\n"); return 0; } while ((dirp = readdir(dp)) != NULL) printf("%s\n", dirp->d_name); closedir(dp); return 0; }