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. Java 设计模式之 策略模式

    思维导图: 我们先来看 STRATEGY 设计模式的通俗解释: 跟不同类型的MM约会,要用不同的策略,有的请电影比较好,有的则去吃小吃效果不错,有的去海边浪漫最合适,但目的都是为了得到 MM 的芳心, ...

  2. scrapy之Request对象

    我们在使用scrapy框架的时候,会经常疑惑,数据流是怎么样在各个组件中间传递的.最近经常用scrapy+selenium爬取淘宝,又因为今天周五心情好,本宝宝决定梳理一下这方面知识. scrapy中 ...

  3. php面试专题---18、MySQL查询优化考点

    php面试专题---18.MySQL查询优化考点 一.总结 一句话总结: 慢查询:查找分析查询速度慢的原因 数据访问:优化查询过程中的数据访问 长难句:优化长难的查询语句 特定类型:优化特定类型的查询 ...

  4. vue分页练习

    <!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...

  5. 跨域资源共享(CORS)-漏洞整理

    绕过方法整理 绕过 - 仅对域名校验 #POC #"Access-Control-Allow-Origin: https://xx.co & Access-Control-Allow ...

  6. (转载)Java 8 认识 HashMap

    原链接:传送门 摘要 HashMap是Java程序员使用频率最高的用于映射(键值对)处理的数据类型.随着JDK(Java Developmet Kit)版本的更新,JDK1.8对HashMap底层的实 ...

  7. jQuery将字符串转换为数字

    1:parseInt(string)  parseInt("1234blue"); //returns 1234 parseInt("123"); //retu ...

  8. Learning OSG programing---osgAnimation(3)

    接下来是用createModel函数创建模型: osg::ref_ptr<osg::Group> createModel(bool overlay, osgSim::OverlayNode ...

  9. CodeForces 739B Alyona and a tree (二分+树上差分)

    <题目链接> 题目大意: 给定一颗带权树,树的根是1,树上每个点都有点权,并且还有边权.现在给出“控制”的定义:对一个点u,设v为其子树上的节点,且$dis(u,v)≤val[v]$,则称 ...

  10. Android应用程序开发中碰到的错误和获得的小经验

    1,Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE Description:这表示手机内存不足,对内存较小的手机经常会出现这样的问题,从 ...