Linux目录操作函数:opendir/readdir/closedir

来源:互联网 发布:售电软件 编辑:程序博客网 时间:2024/05/17 22:51

DIR* opendir (const char * path );

struct dirent* readdir(DIR* dir_handle); 

int closedir(DIR * dir_handle);


1. opendir

头文件:

  #include<sys/types.h>

  #include<dirent.h>

函数原型:

  DIR* opendir (const char * path ); 

功能:

  打开一个目录,在失败的时候返回一个空的指针。

返回值:

       DIR*, DIR构体的原型为:struct  __dirstream

       在linux系统中:

1
2
3
4
5
6
7
8
9
10
11
12
13
   #include<dirent.h>
   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.   */
    };

2. readdir

头文件:

#include<dirent.h>

函数原型:

struct dirent* readdir(DIR* dir_handle); 

功能:

读取opendir 返回值的那个列表

返回值:

返回dirent结构体指针,dirent结构体成员如下,(文件和目录都行)

1
2
3
4
5
6
7
8
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字符 */
}

opendir(3)/readdir(3)/closedir(3)用于遍历目录数据块中的记录。

以下这段代码是打开目录(opendir),读取目录下文件(readdir),关闭目录(closedir)的使用示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
int main()
{
      void DirTravl(const char *dirpath, const char* filename);
      DirTravl("/", ".cpp");
          
      return 0;
}
          
//遍历目录dirpath,查找文件名中包含filename的文件
void DirTravl(const char *dirpath, const char *filename)
{
    struct dirent *dp;
    DIR *dfd;
      char path[256] = {'\0'};
  
    strcpy(path, dirpath);
    if( (dfd = opendir(path)) == NULL )
    {
          printf("Failed to open directory! dir: %s", path);
          return;
    }
             
    while( (dp = readdir(dfd)) != NULL)
    {  
         if(strstr(dp->d_name, filename)!=NULL)
         {
              printf("%s\n",dp->d_name);
         }
    }
    closedir(dfd);
}


另外几个函数:


int mkdir(const char *pathname, mode_t mode);


功能:创建一个名叫pathname的目录,权限(mode & ~umask & 0777)。

           需要  #include<sys/stat.h>

                    #include <sys/types.h>

       

返回值:成功返回0,失败返回-1

     

int rmdir(const char *pathname);  //需要#include <unistd.h>


功能: rmdir() deletes a directory, which must be empty.

      

返回值:成功返回0,失败返回-1


int chdir(const char *path); // #include <unistd.h>

int fchdir(int fd);


功能:chdir函数用于改变当前工作目录。调用参数是指向目录的指针,调用进程需要有搜索整个目录的权限