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

Linux C++ 中的目录操作

2019年05月20日 ⁄ 综合 ⁄ 共 1283字 ⁄ 字号 评论关闭

 

Linux的目录操作一般流程为:打开目录-读取目录(中的文件)-关闭目录。相应的函数为opendir-readdir-closedir,其原型都在/usr/include/dirent.h中定义。
原型:
#include <dirent.h>
DIR *opendir(const char *dirname);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

DIR是directory stream,opendir函数返回dir流类型并供读取函数readdir调用;

readdir返回dirent结构体:
struct dirent
{
#ifndef __USE_FILE_OFFSET64
    __ino_t d_ino;
    __off_t d_off;
#else
    __ino64_t d_ino;
    __off64_t d_off;
#endif
    unsigned short int d_reclen;
    unsigned char d_type;
    char d_name[256];  /* We must not include limits.h! */
};
d_reclen表示记录长度,d_type表示文件类型(具体见后面),d_name表示文件名;

closedir返回0表示关闭成功,-1表示失败。

dirent结构体中的d_tpye的值可以为以下枚举成员:
enum
{
    DT_UNKNOWN = 0,     //未知类型
# define DT_UNKNOWN DT_UNKNOWN
    DT_FIFO = 1,        //管道
# define DT_FIFO DT_FIFO
    DT_CHR = 2,         //字符设备文件
# define DT_CHR  DT_CHR
    DT_DIR = 4,         //目录
# define DT_DIR  DT_DIR
    DT_BLK = 6,         //块设备文件
# define DT_BLK  DT_BLK
    DT_REG = 8,         //普通文件
# define DT_REG  DT_REG
    DT_LNK = 10,        //连接文件
# define DT_LNK  DT_LNK
    DT_SOCK = 12,       //套接字类型
# define DT_SOCK DT_SOCK
    DT_WHT = 14         //
# define DT_WHT  DT_WHT
};

示例:
#include<dirent.h>

  string testPath;
  DIR* pDir = NULL;
  struct dirent* ent = NULL;
  pDir = opendir(testPath.c_str());
  if (NULL == pDir){
    return false;
  }
  while (NULL != (ent=readdir(pDir)))
  {
    if(ent->d_type == 8) //普通文件
    {
      ...
    }
  }
  ...
  closedir(pDir);
  pDir = NULL;

【上篇】
【下篇】

抱歉!评论已关闭.