C++ traverses all the files in the folder

  • 2020-05-27 06:36:25
  • OfStack

Data is stored in multiple files. To read the data, you need to operate on multiple files. You need to locate the name of the file first, and then read and write the file accordingly. Many times involves the multi-file read and write operation, now this realization summary 1, convenient for oneself and others to use. The specific code is as follows:


#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 // Longest path length  
/*---------------------------- 
 *  function  :  Recursively traverse the folder to find all the files it contains  
 *---------------------------- 
 *  function  : find 
 *  access  : public  
 * 
 *  parameter  : lpPath [in]    Directory of folders to traverse  
 *  parameter  : fileList [in]   Stores the traversed file as a file name  
 */ 
void find(char* lpPath,std::vector<const std::string> &fileList) 
{ 
  char szFind[MAX_PATH]; 
  WIN32_FIND_DATA FindFileData; 
  strcpy(szFind,lpPath); 
  strcat(szFind,"\\*.*"); 
  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,"\\"); 
        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;// define 1 A linked list of the names of the resulting files  
  // traverse 1 Subresults of all files , Get a list of file names  
  find("XXXX Specific folder directory ",fileList);// The files in the file list can then be manipulated accordingly  
  // Output the names of all files in the folder  
  for(int i = 0; i < fileList.size(); i++) 
  { 
    cout << fileList[i] << endl; 
  } 
  cout << " Number of documents: " << fileList.size() << endl; 
  return 0; 
} 

conclusion


Related articles: