c 遍歷資料夾

2021-06-12 06:39:52 字數 1160 閱讀 4759

link:

編寫程式遍歷資料夾及其子資料夾下所有檔案,並輸出到標準輸出流或者檔案流。

1. 先考慮在單層目錄下,遍歷所有檔案。以c:\windows為例:

用到資料結構

_finddata_t,檔案資訊結構體的指標。

c++**

struct _finddata_t

;

檔案屬性是無符號整數,取值為相應的巨集:_a_arch(存檔),_a_subdir(資料夾),_a_hidden(隱藏),_a_system(系統),_a_normal(正常),_a_rdonly(唯讀)。容易看出,通過這個結構體,我們可以得到關於該檔案的很多資訊。結合以下函式,我們可以將檔案資訊儲存到這個結構體中:

c++**

//按filename命名規則匹配當前目錄第乙個檔案

_findfirst(_in_ const char * filename, _out_ struct _finddata64i32_t * _finddata);

//按filename命名規則匹配當前目錄下乙個檔案

_findnext(_in_ intptr_t _findhandle, _out_ struct _finddata64i32_t * _finddata);

//關閉_findfirst返回的檔案控制代碼

_findclose(_in_ intptr_t _findhandle);

_findfirst 函式返回的是匹配到檔案的控制代碼,資料型別為long。遍歷過程可以指定檔案型別,這通過filename的賦值來實現,例如要遍歷c:\windows下的所有.exe檔案

c++**

bool transfer(string filename = "c:\\windows\\*.exe", int exenum = 0)

do do

}else

}while (_findnext(handle, &fileinfo) == 0);

_findclose(handle);

fout.close();

}

在判斷有無子目錄的if分支中,由於系統在進入乙個子目錄時,匹配到的頭兩個檔案(夾)是"."(當前目錄),".."(上一層目錄)。需要忽略掉這兩種情況。當需要對遍歷到的檔案做處理時,在else分支中新增相應的**就好

c 遍歷資料夾深度 C 遍歷資料夾獲取資料夾大小

c 遍歷資料夾獲取資料夾大小 都需要引入system.io這個命名空間 第一種方法 public static long getdirectorylength string dirpath 判斷給定的路徑是否存在,如果不存在則退出 if directory.exists dirpath return...

C 遍歷資料夾

下面是一段用於遍歷資料夾內的指定型別檔案的程式 c 遍歷資料夾 author www.icvpr.com blog include include include using namespace std int main int argc,char argv 2.迴圈查詢 do sprintf fi...

C 遍歷資料夾檔案

一 先介紹乙個結構 win32 find data typedef struct win32 find data dword dwfileattributes 檔案屬性 filetime ftcreationtime 檔案建立時間 filetime ftlastaccesstime 檔案最後一次訪問...