C++遍历文件夹目录 C++遍历文件夹目录的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++遍历文件夹目录 C++遍历文件夹目录的方法

Kratze-Jayue   2021-04-21 我要评论

一、方法一:VS2019

// dirlist.cpp : 定义控制台应用程序的入口点。

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

using namespace std;

/************************************************************************/
/* 获取文件夹下所有文件名
输入:
path : 文件夹路径
exd :  所要获取的文件名后缀,如jpg、png等;如果希望获取所有
文件名, exd = ""或"*"
输出:
files : 获取的文件名列表
shao, 20140707
*/
/************************************************************************/
void getFiles(string path, string exd, vector<string>& files)
{
 //cout << "getFiles()" << path<< endl; 
 //文件句柄
 long  hFile = 0;
 //文件信息
 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 ((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";

 //获取该路径下的所有jpg文件
 //getFiles(filePath, "jpg", files);

 //获取该路径下的所有lib文件
 getFiles(filePath, "lib", files);

 //列表文件输出路径
 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();

}

二、方法二:CMD

win+r调出“运行”窗口并输出cmd
输入:cd /d D:\opencv_4.1.0\newbuild\install\x64\vc16\lib 回车 (填自己的路径)
输入:dir /b *.lib *>0.txt 回车 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们