头文件:

复制代码
#include<dirent.h>#include<sys/types.h>opendir():函数原型:DIR * opendir(const char* path);打开一个目录,在失败的时候返回NULL(如果path对应的是文件,则返回NULL)DIR 结构体的原型为:struct_dirstream在linux系统中: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. */};readdir():函数原型:struct dirent * readdir(DIR * dir_handle);本函数读取dir_handle目录下的目录项,如果有未读取的目录项,返回目录项,否则返回NULL。循环读取dir_handle,目录和文件都读返回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字符 */  }closedir():函数原型:int closedir(DIR * dir_handle);
复制代码

程序如下:

复制代码
#include <unistd.h>#include <stdio.h>#include <string.h>#include <stdlib.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>#include <dirent.h>#include <errno.h>#include <sys/stat.h>#include <dirent.h>#include <errno.h>//搜索 指定目录下的所有文件及其子目录下的文件void getFileName(char * dirPath){        DIR *dir=opendir(dirPath);        if(dir==NULL)        {                printf("%s\n",strerror(errno));                return;        }               chdir(dirPath);//进入到当前读取目录        struct dirent *ent;        while((ent=readdir(dir))!=NULL)        {                if(strcmp(ent->d_name,".")==0||strcmp(ent->d_name,"..")==0)                {                        continue;                }                struct stat st;                stat(ent->d_name,&st);                if(S_ISDIR(st.st_mode))                {                        getFileName(ent->d_name);                }                else                {                        printf("%s\n",ent->d_name);                }        }               closedir(dir);        chdir("..");//返回当前目录的上一级目录} int main(int argc, char *argv[]){    getFileName("/home/gexin/program/");    return 0;}
复制代码