C 快速獲取資料夾 目錄 下的所有檔名

2021-10-25 02:12:10 字數 1584 閱讀 8119

說起使用c++操作檔案,最常見的是當屬對單一檔案進行讀寫了,但有時我們需要乙個目錄下的所有檔案又該怎麼快速獲取呢?

這個問題的難點在於如何查詢檔案目錄下的檔案及其數量,以及如何遞迴查詢目錄下的子目錄的檔案及其數量。

我一下子就懵了,趕緊開啟搜尋引擎,在網際網路上找了一圈,發現核心**幾乎都是同一段(原作者已不可考究):

#include

#include

#include

//注意這個標頭檔案

#include

using

namespace std;

//核心函式

void

getfilenames

(string path, vector

& files)

;int

main()

return0;

}//核心**

void

getfilenames

(string path, vector

& files)

else

}while

(_findnext

(hfile,

&fileinfo)==0

);_findclose

(hfile);}

}

筆者在visual studio 2017中測試結果如下:

輸入路徑:d:\\test(或者d:/test),檔案分布為如圖:

輸出結果:

所以上述**應該是正確無誤的。

想必你也注意到了#include這條語句,看起來不太像c/c++標準庫(c++標準庫一般沒有.h,在c++使用c標準庫一般是c***,例如cstdio),而且getfilesnames裡面用了大量該檔案中的巨集。在vs中開啟該檔案,有一些簡單的注釋(不知所云):

// io.h

////

// this file declares the low-level i/o and file handling functionality.

但是這裡使用**#include ** 而不是**#include 「io.h」** 說明 io.h 這個標頭檔案在編譯器的預設搜尋路徑,而不在當前專案路徑。據查, 關於這個io.h的資訊很少,但可以肯定的是它並不是標準c/c++語言的標頭檔案,我用everythig搜尋了該名字,發現在我電腦上以下路徑:d:\windows kits\10\include\10.0.17763.0\ucrt\io.h.

所以 io.h 應該是個vc執行時(runtime)庫,使用它可能在跨平台(unix/linux)上會有問題,謹慎使用。

C 遍歷目錄下的所有資料夾

這個是網上轉的 上乙個也是仿照這個改的 同樣是win32控制台程式 學習!using system using system.collections.generic using system.text using system.io namespace testfileinfo while true...

shell獲取目錄下所有資料夾的名稱並輸出

獲取指定目錄 usr 下所有資料夾的名稱並輸出 shell 1 bin bash 2 方法一 3dir ls l usr awk d 4for i in dir5do 6echo i7 done 8 9 方法二 10for dirin ls usr 11do 12 d dir echo dir 13...

c 遍歷資料夾深度 C 遍歷目錄下所有檔案方法

c 遍歷指定資料夾中的所有檔案 directoryinfo thefolder new directoryinfo folderfullname 遍歷資料夾 foreach directoryinfo nextfolder in thefolder.getdirectories this.listb...