boost库filesystem的应用例子

一  应用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"

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值