欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解C/C++如何獲取路徑下所有文件及其子目錄的文件名

 更新時(shí)間:2023年03月14日 11:34:34   作者:凡人只做一事  
這篇文章主要為大家詳細(xì)介紹了在C/C++中如何獲取路徑下所有文件及其子目錄的文件名,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下

一、功能描述

需要提取某個(gè)文件夾下所有文件名字,當(dāng)包含子目錄時(shí),將子目錄及其路徑獲取到。

二、實(shí)現(xiàn)方式

使用C語(yǔ)言的opendir函數(shù)

  DIR* dp;
  struct dirent* dirp;
  if ((dp = opendir(sdir.c_str())) != NULL) {
      dirp = readdir(dp)
  }

通過(guò)readir讀取到的dirp中包含的d_type具有如下類型及其含義:

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
  };

參考官方文檔可知

DT_UNKNOWN ¶
The type is unknown. Only some filesystems have full support to return the type of the file, others might always return this value.
未知類型
DT_REG
A regular file. 常規(guī)文件
DT_DIR
A directory. 目錄

DT_FIFO
A named pipe, or FIFO. See FIFO Special Files.

DT_SOCK
A local-domain socket. 套接字文件

DT_CHR
A character device. 字符設(shè)備

DT_BLK
A block device. 塊設(shè)備,比如掛載的硬盤之類

DT_LNK
A symbolic link. 鏈接文件

三、代碼實(shí)現(xiàn)

通過(guò)遞歸的方式,獲取該目錄及其子目錄下的所有文件及其路徑名

#include <dirent.h>
#include <vector>
/**
 * @brief GetFiles: 獲取文件夾內(nèi)的所有文件名字
 * @param sdir
 * @param bsubdir: true 包含子目錄下的文件
 * @return
 */
std::vector<std::string> GetFiles(const std::string& sdir = ".",
                                  bool bsubdir = true) {
  DIR* dp;
  struct dirent* dirp;
  std::vector<std::string> filenames;
  if ((dp = opendir(sdir.c_str())) != NULL) {
    while ((dirp = readdir(dp)) != NULL) {
      if (strcmp(".", dirp->d_name) == 0 || strcmp("..", dirp->d_name) == 0)
        continue;
      if (dirp->d_type != DT_DIR)
        filenames.push_back(sdir + "/" + dirp->d_name);
      if (bsubdir && dirp->d_type == DT_DIR) {
        std::vector<std::string> names = GetFiles(sdir + "/" + dirp->d_name);
        filenames.insert(filenames.begin(), names.begin(), names.end());
      }
    }
  }
  closedir(dp);
  return filenames;
}

到此這篇關(guān)于詳解C/C++如何獲取路徑下所有文件及其子目錄的文件名的文章就介紹到這了,更多相關(guān)C++獲取路徑下文件文件名內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論