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. PHP 三元运算符?:的小坑

    $a = ['result'=123]; $b = !empty($a['result'])?:-1; $c = !empty($a['result'])?$a['result']:-1; var_d ...

  2. 小程序页面间传值(处理传值为对象,简单传值直接用options.XX的形式获取)

    bookgoods:function(){ var Json = JSON.stringify(this.data.goods) wx.navigateTo({ url: '/pages/bookgo ...

  3. Vagrant 构建 LNMP 一致环境

    GitHub 地址 <--- 所有文件都在这里 前提条件 安装 Vagrant,VirtualBox. 设置 下载软件并放入 soft 目录 MySQL:mysql-5.7.22-1.el7.x ...

  4. 校内模拟赛 : Rima —— 字典树+树形DP

    首先说一下,对一个刚学Trie树的蒟蒻来说(就是我),这道题是一道好题.Trie树比较简单,所以就不详细写了. Rima 内存限制:256 MiB 时间限制:1000 ms 标准输入输出 题目类型:传 ...

  5. 逻辑回归提高阈值对p和r的影响

    这里我做了一个实验 也就是随着阈值的增大,precision增加或者不变,recall减少或者不变.

  6. 异常检测算法的Octave仿真

    在基于高斯分布的异常检测算法一文中,详细给出了异常检测算法的原理及其公式,本文为该算法的Octave仿真.实例为,根据训练样例(一组网络服务器)的吞吐量(Throughput)和延迟时间(Latenc ...

  7. linux flock()

    表头文件  #include<sys/file.h> 定义函数  int flock(int fd,int operation); 函数说明  flock()会依参数operation所指 ...

  8. msyql join语句执行原理

    首先,我建了一个表t2,里面有1000条数据,有id,a,b三个字段,a字段加了索引 然后我又建立一个t1表,里面有100条数据,和t2表的前一百条数据一致,也是只有id,a,b三个字段,a字段加了索 ...

  9. SpringMvc.xml

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  10. mysql 主从复制 (2)

    今天说一下MySQL的主从复制如何做到! 准备工作: 1.两个虚拟机:我这里用的是CentOS5.5,IP地址分别是192.168.1.101 和192.168.1.105: 101做主服务器,105 ...