读取目录的内容:
读取步骤是:
1、获得目录流;
2、读取目录内容;
3、关闭目录流;
1、获得目录流;
#include<sys/types.h>
#include<dirent.h>
DIR *opendir(const char *name);//成功调用opendir会创建name所指向目录的目录流,也就是打开目录流//
#include<sys/types.h>
#include<dirent.h>
int dirfd(DIR *dir);//成功调用返回目录流dir的文件描述符,也就是获得目录的描述符//
2、从目录流读取:
使用opendir创建一个目录流后,程序可以从目录中读取目录项,使用系统调用readdir(),可以从给定的DIR对象中依次返回目录项:
#include<sys/types.h>
#include<dirent.h>
struct dirent *readdir(DIR *dir);//成功调用会返回dir指向的下个目录项,结构dirent指向目录项,在<dirent.h>中定义:
struct dirent{
ino_t d_ino; //inode number//
off_t d_off; //offset to the next dirent//
unsigned short d_reclen; //length of this record//
unsigned char d_type; //type of file//
char d_name[256]; //filename//
};
要获取整个目录,可以连续的调用readdir(),直到返回NULL时,整个目录读取完毕,如:
#include<unistd.h>
#include<dirent.h>
#include<stdio.h>
int main(int argc,char *argv[]){
char buf[100];
char *pbuf;
pbuf=getcwd(buf,100); //获得当前工作目录//
printf("pbuf=%s\n",pbuf);
printf("buf=%s\n",buf);
DIR *dir;
dir=opendir(pbuf); //打开一个目录流对象//
struct dirent *diren;
while((diren=readdir(dir))!=NULL){//读取目录//
printf("ino_t=%d\n",diren->d_ino);
printf("d_recien=%d\n",diren->d_reclen);
printf("d_type=%d\n",diren->d_type);
printf("d_name=%s\n",diren->d_name);
}
closedir(dir);//关闭目录流//
return 0;
}
3、关闭目录流;
#include<sys/types.h>
#include<dirent.h>
int closedir(DIR *dir);//调用成功将关闭目录流,包括目录文件描述符,并返回0//