1、打开目录 opendir()
#include <sys/types.h> //需要的头文件
#include <dirent.h>
//打开目录
DIR * opendir(const char *name);
参数:
参数1:const char *name//:字符串首地址,打开哪个目录,目录名字符串首地址
返回值:DIR *:目录信息结构体指针(目录结构体的地址)
成功:返回结构体的地址
失败:返回NULL,且设置错误码
DIR *fdopendir(int fd);//内核文件IO操作方式
2、读取目录readdir()
#include <dirent.h>
//读取目录中的文件(普通、目录、...),一次只读取一个文件,内容就是一个文件的基本信息
struct dirent *readdir(DIR *dirp);
参数:
参数1:DIR *dirp//:目录指针,表示读取哪个目录
返回值:struct dirent * :结构体指针,一个地址,地址中存储的是读取到的信息,返回文件信息地址 得到文件信息
struct dirent {
ino_t d_ino; /* Inode number */
inode号
off_t d_off; /* Not an offset; see below */
在目录中的偏移
unsigned short d_reclen; /* Length of this record */
长度
unsigned char d_type; Type of file;not supported by all filesystem types
不用
char d_name[256]; /* Null-terminated filename */
文件名
};
成功:返回文件信息地址
NULL:读取到目录结束,返回NULL,不会设置错误码
错误:返回NULL,设置错误码
3、关闭目录closedir()
#include <sys/types.h>
#include <dirent.h>
//关闭目录
int closedir(DIR *dirp);
参数:
参数1:DIR *dirp//:关闭的哪个打开的目录,目录指针
返回值:
成功:返回0
失败:返回-1.设置错误码