C++基础,输出目录下的所有文件的路径

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:37   1780   0

附上代码,做个笔记。

/*
 输出目录下面的所有文件的路径,如果有子目录,会进到子目录
*/
#include <iostream>
#include <io.h>

using namespace std;

void listFiles(string dir);

int main() {
 //目录路径
 string dir = "C:\\Users\\JSM-SQ\\Desktop\\face\\att_faces";
 listFiles(dir);
 system("pause");
 return 1;
}

void listFiles(string dir) {
 //在目录后面加上"\\*.*"进行第一次搜索
 string newDir = dir + "\\*.*";
 //用于查找的句柄
 intptr_t handle;
 struct _finddata_t fileinfo;
 //第一次查找
 handle = _findfirst(newDir.c_str(), &fileinfo);

 if (handle == -1) {
  cout << "无文件" << endl;
  system("pause");
  return;
 }

 do
 {
  if (fileinfo.attrib & _A_SUBDIR) {//如果为文件夹,加上文件夹路径,再次遍历
   if (strcmp(fileinfo.name, ".") == 0 || strcmp(fileinfo.name, "..") == 0)
    continue;

   // 在目录后面加上"\\"和搜索到的目录名进行下一次搜索
   newDir = dir + "\\" + fileinfo.name;
   listFiles(newDir.c_str());
  }
  else{
   string file_path = dir + "\\" + fileinfo.name;
   cout << file_path.c_str() << endl;
  }
 } while (!_findnext(handle, &fileinfo));

 _findclose(handle);
 return;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP