1. 程式人生 > >【筆記】window下 使用c++遍歷資料夾及其子資料夾和檔案,並列印檔案路徑及各檔案內容

【筆記】window下 使用c++遍歷資料夾及其子資料夾和檔案,並列印檔案路徑及各檔案內容

這兩天一直在學習如何使用c++遍歷資料夾、讀取檔案內容和寫入檔案。

話不多說,直接上程式碼


/*
* 檔案功能:遞迴遍歷資料夾,遍歷資料夾及其子資料夾和檔案.列印資料夾名稱、檔名稱和檔案數目
*
*
* 參考:https://www.cnblogs.com/collectionne/p/6792301.html
* 控制代碼(handle):是Windows用來標誌應用程式中建立的或是使用的唯一整數,Windows大量使用了控制代碼來標識物件。

* 原型宣告:extern char *strcat(char *dest, const char *src);

*      函式功能:把src所指字串新增到dest結尾處(覆蓋dest結尾處的'\0')。

* 原型宣告:char *strcpy(char* dest, const char *src);

*      函式功能:把從src地址開始且含有NULL結束符的字串*複製到以dest開始的地址空間。

*/

#include "stdafx.h"  
#include <iostream>
#include <cstring>        // for strcpy_s(), strcat_s()
#include <io.h>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

void listFiles(const char * dir, std::vector<const std::string> &fileList);

int main()
{
std::vector<const std::string> fileList; //定義一個存放結果檔名稱的連結串列  

listFiles("D:/VS2017/VS2017 DATA/test/test1/mulu", fileList); // 這裡輸目錄路徑,絕對路徑

for (int i = 0; i < fileList.size(); i++)
{
cout << fileList[i] << endl;
}
cout << "檔案數目:" << fileList.size() << endl;
// 列印檔案數目

return 0;

}


/*----------------------------
* 功能 : 遞迴遍歷資料夾,找到其中包含的所有檔案
*----------------------------
* 函式 : listFiles
* 訪問 : public
*
* 引數 : dir [in]    需遍歷的資料夾目錄
* 引數 : fileList [in] 以檔名稱的形式儲存遍歷後的檔案

*/

void listFiles(const char * dir, std::vector<const std::string> &fileList)
{
char dirNew[200];
strcpy_s(dirNew, dir);
strcat_s(dirNew, "\\*.*");  // 在目錄後面加上"\\*.*"進行第一次搜尋.

intptr_t handle;
_finddata_t findData; // _finddata_t是儲存檔案各種資訊的結構體

handle = _findfirst(dirNew, &findData);
if (handle == -1) // 檢查是否成功
return;
do
{
if (findData.attrib & _A_SUBDIR) // 目錄
{
if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
continue;

cout << findData.name << "\t<dir>\n"; // 列印資料夾的名稱
//fileList.push_back(findData.name); // 列印資料夾的名稱

// 在目錄後面加上"\\"和搜尋到的目錄名進行下一次搜尋
strcpy_s(dirNew, dir);
strcat_s(dirNew, "\\");
strcat_s(dirNew, findData.name);

listFiles(dirNew, fileList);
}
else // 檔案
{
fileList.push_back(findData.name); // 列印檔案的名稱,並且後面可以列印檔案的數目
}

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

_findclose(handle);    // 關閉搜尋控制代碼

}

測試輸出結果如下:


如果要遍歷資料夾的所有檔案,並輸出檔案路徑和檔案內容,我上傳了我的程式碼,歡迎瀏覽

點選開啟連結 https://download.csdn.net/download/yaodaoji/10344109

列印資訊如下:


可以再此基礎上對檔案進行 寫入檔案和讀取檔案。