一、打开一个目录
函数名称:opendir
函数原型:DIR * opendir(const char* path);
函数功能:打开一个目录,在失败的时候返回NULL(如果path对应的是文件,则返回NULL)
返回值:
DIR 结构体的原型为:struct_dirstream
在linux系统中:
typedef struct __dirstream DIR;
{
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<dirent.h>
#include<sys/types.h>
二、读取目录
函数名称:readdir
函数原型:struct dirent * readdir(DIR * dir_handle);
函数功能:本函数读取dir_handle目录下的目录项,如果有未读取的目录项,返回目录项,否则返回NULL。
返回值:
返回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字符 */
}
头文件:#include<dirent.h>
#include<sys/types.h>
三、关闭目录
函数名称:closedir
函数原型:int closedir(DIR * dir_handle);
函数功能:本函数读取dir_handle目录下的目录项,如果有未读取的目录项,返回目录项,否则返回NULL。
demo:列举当前目录下的所有目录和文件 ls
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(void)
{
DIR* dir=opendir(".");//打开当前目录
struct dirent *de;
while((de=readdir(dir))!=NULL){//尝试读取文件或目录
if(strncmp(de->d_name,".",1)==0){//如果是当前目录就忽略
continue;
}
printf("%s\n",de->d_name);//打印目录名
}
closedir(dir);//关闭目录
exit(EXIT_SUCCESS);
}
输出: