温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++怎么遍历文件夹目录

发布时间:2020-08-03 11:44:43 来源:亿速云 阅读:172 作者:小猪 栏目:编程语言

小编这次要给大家分享的是C++怎么遍历文件夹目录,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

一、方法一: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 回车 

看完这篇关于C++怎么遍历文件夹目录的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI