现在的位置: 首页 > 综合 > 正文

Linux c 目录管理—目录简单遍历 opendir、readdir、scandir

2017年12月14日 ⁄ 综合 ⁄ 共 1837字 ⁄ 字号 评论关闭

Linux c 目录管理:

   目录的简单遍历:

 

opendir函数:

       函数原型:
DIR * opendir(const char* path);
打开一个目录,在失败的时候返回NULL(如果path对应的是文件,则返回NULL)

 

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 在目录文件中的偏移 */

  unsignedshort d_reclen; /* length of this d_name 文件名长 */

  unsignedchar 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<stdio.h>

#include<unistd.h>

#include<dirent.h>

#include<stdlib.h>

 

int  main()

{

       DIR *d;

       Struct dirent *de;

       //打开目录

       d=opendir(“../dir”);

       if(d==NULL)

       {

              printf(“opendir error:%m”);

              exit(-1);

       }

       //读取目录

       while(de=readdir(d))

       {

                printf(“%s\t%d\n”,de->d_name,de->d_type);

        }

       //关闭目录

       closedir(d);

}

 

scandir函数:

int scandir(constchar*dirname,//目录名

                            structdirent***namelist,//返回目录列表

                            int (*)(structdirent*),//回调函数,过滤目录

                                                                                                         //NULL:不过滤

                            int (*)(structdirent*,struct dirent*)//排序返回目录

                                                                                    //NULL:不排序

                            );    

                     返回:    >=0 目录个数 、=-1 目录查找失败

 

例子:

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include<dirent.h>

 

 

int  main()

{

     struct dirent **d;

     int r,i,

     r=scandir(“/home”,&d,NULL,NULL);

     printf(“子目录个数:%d\n”,r);

     //遍历子目录

/*    for(i=0;i<r;i++)

     {

         printf(“%s\n”,d[i]->d_name);

     }

*/

 

     while(*d)

     {

         printf(“%s\n”,(*d)->d_name);

         d++;

     }

}|

 

 

 

抱歉!评论已关闭.