一 应用filesysytem进行目录查找文件demo。
#include <iostream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
using namespace boost;
using namespace boost::filesystem;
using namespace std;
typedef recursive_directory_iterator rd_iterator; //及递归地在所有子目录的目录条目上迭代的输入迭代器 (InputIterator) 。迭代顺序是未指定的,除了只造访一次每个目录条目。
optional<path> find_file(const path&dir, const string& filename)
{
typedef optional<path> result_type;
if (!exists(dir) || !is_directory(dir))
{
return result_type();
}
rd_iterator end;
for (rd_iterator pos(dir); pos != end; ++pos)
{
if (!is_directory(*pos) && pos->path().filename() == filename) {
return result_type(pos->path());
std::cout << pos->path() << std::endl;
}
std::cout << pos->path() << std::endl;
}
return result_type();
}
int main()
{
optional<path> r = find_file("E:\\vscode\\BoostFileSystem", "BoostFileSystem.sln");
if (r)
{
std::cout << *r << std::endl;
}
else {
std::cout << "file not found" << std::endl;
}
while (1);
}
二:选择路径中的你需求的部分:
#include "boost/filesystem.hpp" // 包含所有需要的 Boost.Filesystem 声明
#include <iostream> // 使用 std::cout
namespace fs = boost::filesystem;
// 宏FSTEST:测试f的成员函数,输出成员函数名和结果
#define FSTEST(x) std::cout << #x##": " << f.x << std::endl
int main()
{
fs::path f("//folder1//folder2//folder3//filename.ext");
FSTEST(string());
FSTEST(root_name());
FSTEST(root_directory());
FSTEST(root_path());
FSTEST(relative_path());
FSTEST(filename());
FSTEST(parent_path());
FSTEST(stem());
FSTEST(extension());
FSTEST(replace_extension("new"));
char buf[] = "hello";
FSTEST(append(buf, buf + sizeof(buf)));
FSTEST(remove_filename());
while (1);
return 0;
}
输出:
string(): //folder1//folder2//folder3//filename.ext
root_name(): "//folder1"
root_directory(): "/"
root_path(): "//folder1/"
relative_path(): "folder2//folder3//filename.ext"
filename(): "filename.ext"
parent_path(): "//folder1//folder2//folder3"
stem(): "filename"
extension(): ".ext"
replace_extension("new"): "//folder1//folder2//folder3//filename.new"
append(buf, buf + sizeof(buf)): "//folder1//folder2//folder3//filename.new\hello "
remove_filename(): "//folder1//folder2//folder3//filename.new"