C++ method to traverse the folder directory
- 2020-08-22 22:19:44
- OfStack
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;
/************************************************************************/
/* Gets all file names under the folder
Input:
path : Folder path
exd : The filename suffix to obtain, for example jpg , png And so on; If you want to get all of them
The file name , exd = "" or "*"
Output:
files : Gets a list of file names
shao, 20140707
*/
/************************************************************************/
void getFiles(string path, string exd, vector<string>& files)
{
//cout << "getFiles()" << path<< endl;
// File handle
long hFile = 0;
// File 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 it's a folder, it still has folders in it , The iteration of the
// If it is 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";
// Gets all under the path jpg file
//getFiles(filePath, "jpg", files);
// Gets all under the path lib file
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();
}
Method 2: CMD
win+r brings up the Run window and outputs cmd
Type: cd /d D:\ opencv_4.1.0 \newbuild\install\x64\vc16\lib enter (fill in your own path)
Input: dir /b *.lib *
>
0. txt enter