【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

打印信息如下:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章