溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C/C++怎么獲取路徑下所有文件及其子目錄的文件名

發(fā)布時間:2023-03-14 14:10:06 來源:億速云 閱讀:426 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了C/C++怎么獲取路徑下所有文件及其子目錄的文件名的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇C/C++怎么獲取路徑下所有文件及其子目錄的文件名文章都會有所收獲,下面我們一起來看看吧。

一、功能描述

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

二、實現(xiàn)方式

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

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

通過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. 鏈接文件

三、代碼實現(xiàn)

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

#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++怎么獲取路徑下所有文件及其子目錄的文件名”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“C/C++怎么獲取路徑下所有文件及其子目錄的文件名”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++ c
AI