Method of traversing folder directory in C + +

Time:2021-2-20

1、 Method 1: vs2019

//  dirlist.cpp  : defines the entry point for the console application.

//#include "stdafx.h"
#include <string>
#include <io.h>
#include <vector>
#include <iostream>

using namespace std;

/************************************************************************/
/*Get all the file names in the folder
Input:
Path: folder path
Exd: the file name suffix to get, such as JPG, PNG, etc.; if you want to get all
File name, Exd = "or" * "
Output:
Files: get the list of file names
shao, 20140707
*/
/************************************************************************/
void getFiles(string path, string exd, vector<string>& files)
{
 //cout << "getFiles()" << path<< endl; 
 //File handle
 long  hFile = 0;
 //Document information
 struct _finddata_t fileinfo;
 string pathName, exdName;

 if (0 != strcmp(exd.c_str(), ""))
 {
 exdName = "\\*." + exd;
 }
 else
 {
 exdName = "\\*";
 }

 if ((hFile = _findfirst(pathName.assign(path).append(exdName).c_str(), &fileinfo)) != -1)
 {
 do
 {
  //cout << fileinfo.name << endl; 

  //If there is still a folder in the folder, iterate it
  //If not, join the list
  if ((fileinfo.attrib & _A_SUBDIR))
  {
  if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
   getFiles(pathName.assign(path).append("\\").append(fileinfo.name), exd, files);
  }
  else
  {
  if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
   files.push_back(pathName.assign(path).append("\\").append(fileinfo.name));
  }
 } while (_findnext(hFile, &fileinfo) == 0);
 _findclose(hFile);
 }
}

void main()
{
 cout << "start list" << endl;
 vector<string> files;
 const char* filePath = "D:\\opencv_4.1.0\\newbuild\\install\\x64\\vc16\\lib";

 //Get all JPG files in this path
 //getFiles(filePath, "jpg", files);

 //Get all lib files in this path
 getFiles(filePath, "lib", files);

 //List file output path
 FILE* fp;
 fopen_s(&fp, "d:\\dir_list.txt", "w");

 int size = files.size();
 for (int i = 0; i < size; i++)
 {
 cout << files[i] << endl;

 fputs(files[i].c_str(), fp);
 fputs("\n", fp);

 }
 fclose(fp);

 cout << "end list" << endl;
 getchar();

}

2、 Method 2: CMD

Win + R calls up the “run” window and outputs CMD
Input: CD / D D_ 4.1.0 / newbuild / install / x64 / vc16 / Lib
Enter: dir / b *. Lib * > 0.txt enter

This article about the method of C + + traversing the folder directory is introduced here. For more content about C + + traversing the folder directory, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!