The library Boost.Filesystem makes it easy to work with files and directories.

Paths

Paths can be build by passing a string to the constructor of boost::filesystem::path. None of the constructors of boost::filesystem::path validate paths or check whether the given file or directory exists. Thus, boost::filesystem::path can be instantiated even with meaningless paths.

1. retrieving paths from boost::filesystem::path

#include <boost/filesystem.hpp>
#include <iostream> using namespace boost::filesystem; int main()
{
path p("C:\\Windows\\System");
std::cout << p.native() << std::endl;
std::cout << p.string() << std::endl;
std::cout << p.generic_string() << std::endl; return ;
}

The return value of member functions returning native paths depends on the operating system the program is executed on. The return value of member functions returning generic paths is independent of the operating system. Generic paths uniquely identify files and directories independently from the operating system and therefore make it easy to write platform-independent code.

2. accessing compoenents of a path

include <boost/filesystem.hpp>
#include <iostream> using namespace boost::filesystem; int main()
{
path p{"C:\\Windows\\System"};
std::cout << p.root_name() << std::endl;
std::cout << p.root_directory() << std::endl;
std::cout << p.root_path() << std::endl;
std::cout << p.relative_path() << std::endl;
std::cout << p.parent_path() << std::endl;
std::cout << p.filename() << std::endl; return ;
}

If example above is executed on Linux, the returned values are different. Most of the member functions return an empty string, except relative_path() and filename(), which return "C:\Windows\System". This means that the string “C:\\Windows\\System” is interpreted as a file name on Linux, which is understandable given that it is neither a portable encoding of a path nor a platform-dependent encoding on Linux. Therefore, Boost.Filesystem has no choice but to interpret it as a file name.

Boost.Filesystem provides additional member functions to verify whether a path contains a specific substring. These member functions are: has_root_name(), has_root_directory(), has_root_path(), has_relative_path(), has_parent_path(), and has_filename().

3. receiveing file name and file extension; iterating over components of a path

#include <boost/filesystem.hpp>
#include <iostream> using namespace boost::filesystem; int main()
{
path p("photo.jpg");
std::cout << p.stem() << std::endl;
std::cout << p.extension() << std::endl; path p2("C:\\Windows\\System");
for (const path &pp : p2)
std::cout << pp << std::endl; return ;
}

Files and Directories

Boost.Filesystem provides two variants of the functions that behave differently in case of an error:

The first variant throws an exception of type

boost::filesystem::filesystem_error. This class id derived from boost::system::system_error and thus fits into the Boost.System framework.

The second variant expects an object of type boost::system::error_code as an additional parameter. This object is passed by reference and can be examined after the function call.

1.

#include <boost/filesystem.hpp>
#include <iostream>
#include <ctime> using namespace boost::filesystem; int main() {
path p("C:\\"); try {
file_status s = status(p);
std::cout << std::boolalpha << is_directory(s) << std::endl;
} catch (filesystem_error& e) {
std::cerr << e.what() << std::endl;
} path p2("/home/sss/program");
std::cout << is_directory(p2) << std::endl; path p3("/home/sss/program/c++/boost/filesystem/status.cpp");
boost::system::error_code ec;
boost::uintmax_t filesize = file_size(p3, ec);
if (!ec) {
std::cout << filesize << std::endl;
} else {
std::cout << ec << std::endl;
} std::time_t t = last_write_time(p3);
std::cout << std::ctime(&t) << std::endl; path p4(".");
space_info s = space(p4);
std::cout << s.capacity << std::endl;
std::cout << s.free << std::endl;
std::cout << s.available << std::endl; return ;
}

boost::filesystem::status() queries the status of a file or directory. This function returns an object of tpe boost::filesystem::file_status which can be passed to additional helper functions for evaluation. boost::filesystem::is_directory() returns true if the status for a directory was queried.Other functions are available, including boost::filesystem::is_regular_file(), boost::filesystem::is_symlink(), and boost::filesystem::exists(), all of which return a value of type bool.

The function boost::filesystem::file_size() returns the size of a file in bytes. The return value is of type boost::uintmax_t, which is a type definition for unsigned long long. The type is provided by Boost.Integer.

boost::filesystem::space() returns an object of type boost::filesystem::space_info, which provides three public member variables: capacity, free, and available, all of type boost::uintmax_t. The disk space is in bytes.

2.

#include <boost/filesystem.hpp>
#include <iostream> using namespace boost::filesystem; int main() {
path p("./test");
try {
if (create_directory(p)) {
rename(p, "./test2");
boost::filesystem::remove("./test2");
}
} catch(filesystem_error& e) {
std::cerr << e.what() << std::endl;
} std::cout << absolute("create_directory.cpp") << std::endl; std::cout << current_path() << std::endl;
current_path("/home/sss/program/c++/boost");
std::cout << current_path() << std::endl;
return ;
}

It's not always an object of type boost::filesystem::path that is passed to functions, but rather a simple string. This is possible because boost::filesystem::path provides a non-explict constructor that will convert strings to objects of type. Additional functions such as create_symlink() to create symbolic links or copy_file() and copy_directory() to copy files and directories are available as well.

If the function boost::filesystem::current_path() is called without parameters, the current working directory is returned. If an object of type boost::filesystem::path is passed, the current working directory is set.

Directory Iterators

Boost.Filesystem provides the iterator boost::filesystem::directory_iterator to iterate over files in a directory.

#include <boost/filesystem.hpp>
#include <iostream> using namespace boost::filesystem; int main() {
path p = current_path();
directory_iterator it(p2);
while (it != directory_iterator()) {
std::cout << *it++ << std::endl;
} path p2("/home/test/program");
recursive_directory_iterator it(p2);
while (it != recursive_directory_iterator()) {
std::cout << *it++ << std::endl;
} return ;
}

boost::filesystem::directory_iterator is initialized with a path to retrieve an iterator pointing to the beginning of a directory. To retrieve the end of a directory , the class must be instantiated with the default constructor.

To recursively iterate over a directory and subdirectories, Boost.Filesystem provides the iterator boost::filesystem::recursive_directory_iterator.

boost Filesystem的更多相关文章

  1. Boost::filesystem 使用小笔记

    今天拿起手要用C++写个小工具,从指定的目录递归遍历文件,然后做一下处理.又翻了一下boost的filesystem库.小结一下,希望能加深印象,免得下次又要查看文档. 1. path对象就是一个跨平 ...

  2. C++ 檔案、資料夾、路徑處理函式庫:boost::filesystem

    原帖:https://tokyo.zxproxy.com/browse.php?u=uG7kXsFlW1ZmaxKEvCzu8HrCJ0bXIAddA1s5dtIUZ%2FYzM1u9JI7jjKLT ...

  3. [boost][filesystem] 扫描给定目录下所有项

    Intro. Boost的filesystem可以用来扫描给定目录下的所有项. 实现 具体实现代码如下: 需要包含的头文件和使用的命名空间: #include <boost/filesystem ...

  4. boost::filesystem总结

    boost::filesystem是Boost C++ Libraries中的一个模块,主要作用是处理文件(Files)和目录(Directories).该模块提供的类boost::filesyste ...

  5. boost::filesystem经常使用使用方法具体解释

    提示: filesystem库提供了两个头文件,一个是<boost/filesystem.hpp>,这个头文件包括基本的库内容.它提供了对文件系统的重要操作. 同一时候它定义了一个类pat ...

  6. MongDB备份error: boost::filesystem::create_directory

    用dump 备份一直提示一个error "error: boost::filesystem::create_directory: The filename, directory name, ...

  7. C++目录遍历:使用第三方库boost.filesystem等

    1. opencv 目录文件遍历 注释:2014 0814 这个代码是基于java的,Java使用托管代码进行目录管理,C++就不那么跨平台了. 原文链接:http://blog.csdn.net/z ...

  8. (九)boost库之文件处理filesystem

    (九)boost库之文件处理filesystem   filesystem库是一个可移植的文件系统操作库,它在底层做了大量的工作,使用POSIX标准表示文件系统的路径,使C++具有了类似脚本语言的功能 ...

  9. Boost学习之可移植路径操作--filesystem

    Boost.Filesystem 库为对路径.文件和目录进行查询和操作提供了可移植的工具,已经被C++标准委员会接纳包含到TR2中. 编译 使用Boost.Filesystem 库之前要先编译它,请参 ...

随机推荐

  1. ProxyImpl 类

    package com.test.mvp.mvpdemo.mvp.v7.proxy; import com.test.mvp.mvpdemo.mvp.v7.basemvp.BasePresenter; ...

  2. Hive学习之路(三)Hive处理中文乱码

    Hive注释中文乱码 创建表的时候,comment说明字段包含中文,表成功创建之后,中文说明显示乱码 create external table movie( userID int comment ' ...

  3. 牛客提高D2t1 ACGT

    分析 用map维护一下每种字符串当前有几个即可 代码 #include<iostream> #include<cstdio> #include<cstring> # ...

  4. 使用Flask+nginx+uwsgi+Docker部署python应用

    https://www.cnblogs.com/vh-pg/p/11731637.html

  5. Dapper - a simple object mapper for .Net

    Dapper - a simple object mapper for .Net Release Notes Located at stackexchange.github.io/Dapper Pac ...

  6. Grafana+Prometheus系统监控之Redis

    REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...

  7. composer的自动加载机制(autoload)

    composer的出现真是让人们眼前一亮,web开发从此变成了一件很『好玩』的事情,开发一个CMS就像在搭积木,从packagist中取出『积木』搭建在自己的代码中,一点一点搭建出一个属于自己的王国. ...

  8. springboot jpa 级联操作及测试问题 (@Transactional与@Test)

    前言:测试springboot版本     :springBootVersion = '2.0.5.RELEASE' 一 :搬运@Transactional B. 如果加了事务,必须做好开发环境测试( ...

  9. LeetCode 112. Path Sum 动态演示

    给一个目标值,判断一棵树从根到叶子是否至少有一条路径加起来的和等于目标值 比较典型的深度优先算法. 引入一个全局变量bResult, 一旦找到一条,就不再搜索其他的了. class Solution ...

  10. 20190819 On Java8 第九章 多态

    第九章 多态 向上转型回溯 可扩展性 由于多态机制,在一个设计良好的面向对象程序中,许多方法,只与基类接口通信.这样的程序是可扩展的,因为可以从通用的基类派生出新的数据类型,从而添加新的功能.那些操纵 ...