Introduction
在Windows系统下获取某个目录下的所有文件名有多种方法,比如:利用Windows自带的函数(包含#include <Windows.h>),利用boost库,利用C++的新特性。
这里利用C++14/17中的文件管理系统filesystem来获取某个目录下的所有文件名,这种方法十分简单,几行代码轻松搞定。
如果编译器支持C++17,将下列代码
// C++14
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
改为
// c++17
#include <filesystem>
namespace fs = std::filesystem;
Code
以下是完整代码,将生成的exe文件放入需要读取文件名的路径下,运行exe即可。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <experimental/filesystem> //C++14
namespace fs = std::experimental::filesystem;
void getFileNames(const std::string dir, std::vector<std::string>& vFileNames, bool extension = 1)
{
for (const auto & entry : fs::directory_iterator(dir))
{
if (1 == extension)
{
// with extension
vFileNames.push_back(entry.path().filename().string());
}
else if (0 == extension)
{
// without extension
std::string fileName;
fileName = entry.path().filename().string();
int pos = fileName.rfind(".");
vFileNames.push_back(std::string(fileName, 0, pos));
fileName.clear();
}
}
}
int main(int argc, char* argv[])
{
// get current directory
std::string argv_str(argv[0]);
std::string dir = argv_str.substr(0, argv_str.find_last_of("\\"));
// get current execute's name
std::string exeName1 = argv_str.substr(argv_str.find_last_of("\\") + 1);
std::string exeName0 = exeName1.substr(0, exeName1.find_last_of("."));
std::cout << "current path is " << dir << std::endl;
std::cout << "output files' name with extension or not?" << std::endl;
std::cout << "1: with extension" << std::endl;
std::cout << "0: without extension" << std::endl;
// with extension or not
bool sign = 1;
std::cin >> sign;
std::cout << std::endl;
// delete execute's name
std::vector<std::string> vFileNames;
getFileNames(dir, vFileNames, sign);
std::string exeName = (sign == 1 ? exeName1 : exeName0);
std::vector<std::string>::const_iterator iter =
std::find(vFileNames.begin(), vFileNames.end(), exeName);
vFileNames.erase(iter);
// show and output all file's name
std::ofstream ofile(dir + "//fileName.txt");
for (std::string fileName : vFileNames)
{
std::cout << fileName << std::endl;
ofile << fileName << std::endl;
}
ofile.close();
system("pause");
return 0;
}
Reference
How can I get the list of files in a directory using C or C++?
HOW TO LIST THE FILES IN A DIRECTORY IN C++