C++17读取某个文件夹下面文件和子文件夹及其所有文件

xiaoxiao2021-02-28  64

使用了C++17很好用的filesystem, 再也不用boost的文件系统了,上代码,实现了读取某个文件夹下面文件和子文件夹及其所有文件!

#include <fstream>

#include <iostream>

#include <string> #include <sstream> #include <vector> #include <io.h> #include <experimental\filesystem> using namespace std; namespace fs = std::experimental::filesystem; void getAllFiles(fs::path strPath, vector<fs::path>& files) { for (auto& fe : fs::directory_iterator(strPath)) { auto fp = fe.path(); auto fFiename = fp.filename(); cout << fFiename << endl; if(fs::is_directory(fe)) {

if (fFiename != "." && fFiename != "..")

                        {

files.push_back(fp);

getAllFiles(fp, files);

         }

                 }

else { files.push_back(fp);

}              

  } } int main() { fs::path DATA_DIR = "D:\\test"; cout << DATA_DIR.filename() << endl; if (!fs::exists(DATA_DIR)) { return -1; } vector<fs::path> files; string DistAll = "C:\\dir.txt"; getAllFiles(DATA_DIR, files);           //所有文件与文件夹的路径都输出 ofstream ofn(DistAll, ios::app);                  //输出文件流 int size = files.size(); int  FaiNum = 0; ofn << size << endl; for (int i = 0; i<size; i++) { ofn << files[i] << endl; } ofn.close(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-2621921.html

最新回复(0)