问题:
想要遍历指定文件夹下的文件,寻找到符合某条件的文件。
思路:
这里只记录C++17中使用 boost::filesystem 实现遍历文件夹的方法。
解决:
1、遍历获取指定路径下所有文件:使用boost::filesystem::path 和 boost::filesystem::directory_iterator。
注意:boost::filesystem::directory_iterator 不包含子文件夹内文件。
如果想迭代获取指定文件夹下所有文件(包含子文件夹内的文件)则使用boost::filesystem::recursive_directory_iterator。
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/directory.hpp"
#include "boost/filesystem/operations.hpp"
//遍历获取指定路径下文件
bool GetFiles(std::vector<CString>& vecFiles, const CString& sPath)
{
try
{
vecFiles.clear();
boost::filesystem::path path(sPath);
for (const auto& iter : boost::filesystem::directory_iterator(path))
{
if (boost::filesystem::is_directory(iter.path()))//过滤子文件夹
continue;
CString sFile = iter.path().filename().string().c_str();
vecFiles.push_back(sFile);
}
return true;
}
catch (const std::exception& error)
{
CString sError = error.what();
}
return false;
}
int main()
{
std::vector<CString> vecFiles;
CString sPath = _T("D:\\");//指定路径
if (GetFiles(vecFiles, sPath))
{
for (const CString& file : vecFiles)
acutPrintf(_T("\n %s"), file);
}
return 0;
}
输出结果:以及指定路径下内容
2、boost::filesystem 几个说明:
//boost::filesystem::path
boost::filesystem::path path;
path.string(); //!< 字符串形式的文件绝对路径: D:\\xxx.xml
path.filename(); //!< 文件名: xxx.xml 包含文件名称+文件扩展名后缀
path.stem(); //!< 文件名称: xxx 不包含文件扩展名
path.extension(); //!< 文件扩展名: xml
//boost::filesystem几个函数
boost::filesystem::status() //!<查询文件或目录的状态,返回的是boost::filesystem::file_status类型的对象
boost::filesystem::is_directory() //!<判断是否是目录
boost::filesystem::is_empty() //!<判断是否为空
boost::filesystem::is_regular_file() //!<判断是否是普通文件
boost::filesystem::is_symlink() //!<判断是否是链接文件(后缀为lnk)
boost::filesystem::exists() //!<判断是否存在
boost::filesystem::file_size() //!<返回文件的size,按bytes计算
boost::filesystem::last_write_time() //!<返回文件最后一次修改的时间
boost::filesystem::space() //!<返回磁盘的总空间和剩余空间,
boost::filesystem::create_directory() //!<创建目录
boost::filesystem::create_directories() //!<递归创建整个目录结构
boost::filesystem::remove() //!<删除目录
boost::filesystem::remove_all() //!<递归删除整个目录结构
boost::filesystem::rename() //!<重命名目录
boost::filesystem::copy_file() //!<复制文件
boost::filesystem::copy_directory() //!<复制目录
boost::filesystem::absolute() //!<获取文件或目录的绝对路径
boost::filesystem::current_path() //!<如果没有参数传入,则返回当前工作目录;否则,则将传入的目录设为当前工作目录