數據分多個文件存儲,讀取數據就需要對多個文件進行操作。首先就需要定位到文件的名字,之后再對文件進行相應的讀寫操作。多次涉及多文件的讀寫操作,現將這個實現總結一下,方便自己和他人使用。具體代碼如下:
#include "stdafx.h" #include <stdio.h> #include<iostream> #include<vector> #include <Windows.h> #include <fstream> #include <iterator> #include <string> using namespace std; #define MAX_PATH 1024 //最長路徑長度 /*---------------------------- * 功能 : 遞歸遍歷文件夾,找到其中包含的所有文件 *---------------------------- * 函數 : find * 訪問 : public * * 參數 : lpPath [in] 需遍歷的文件夾目錄 * 參數 : fileList [in] 以文件名稱的形式存儲遍歷后的文件 */ void find(char* lpPath,std::vector<const std::string> &fileList) { char szFind[MAX_PATH]; WIN32_FIND_DATA FindFileData; strcpy(szFind,lpPath); strcat(szFind,"http://*.*"); HANDLE hFind=::FindFirstFile(szFind,&FindFileData); if(INVALID_HANDLE_VALUE == hFind) return; while(true) { if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(FindFileData.cFileName[0]!='.') { char szFile[MAX_PATH]; strcpy(szFile,lpPath); strcat(szFile,"http://"); strcat(szFile,(char* )(FindFileData.cFileName)); find(szFile,fileList); } } else { //std::cout << FindFileData.cFileName << std::endl; fileList.push_back(FindFileData.cFileName); } if(!FindNextFile(hFind,&FindFileData)) break; } FindClose(hFind); } int main() { std::vector<const std::string> fileList;//定義一個存放結果文件名稱的鏈表 //遍歷一次結果的所有文件,獲取文件名列表 find("XXXX具體文件夾目錄",fileList);//之后可對文件列表中的文件進行相應的操作 //輸出文件夾下所有文件的名稱 for(int i = 0; i < fileList.size(); i++) { cout << fileList[i] << endl; } cout << "文件數目:" << fileList.size() << endl; return 0; }
總結
以上所述是小編給大家介紹的C++遍歷文件夾下所有文件,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答
圖片精選