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. Flask学习 2修改路由规则 传入参数访问url

    #!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: cxa @file: flask0 ...

  2. MyView.java 自己画的view

    package myapplication21.lum.com.mycanvas; import android.content.Context;import android.graphics.Can ...

  3. 牛客提高D3t1 破碎的矩阵

    分析 我们发现如果行的异或和等于列的异或和那么对于n-1行m-1列的所有数的选择都是任意的 因为一定可以在它的行末/列末选一个合适的数是的整体满足 但是我们发现对于右下角那一个数是否满足存疑 我们设矩 ...

  4. Git学习及使用

    一.认知git理论 1.git出现的背景 版本控制 版本控制是一种记录一个或若干文件内容变化,以便将来查阅特定版本修订情况的系统. 许多人习惯用复制整个项目目录的方式来保存不同的版本,或许还会改名加上 ...

  5. vue- 指令v-if 与指令v-show的区别

    区别1: v-if :可以根据表达式的值在DOM中生成或移除一个元素. v-show:可以根据表达式的值来显示或者隐藏HTML元素.当v-show赋值为false时,元素被隐藏,此时查看代码时,该元素 ...

  6. poi3617Best Cow Line ——贪心法

    给定长度为N(1≤N≤2000)的字符串S,要构造一个长度为N的字符串T.期初,T是一个空串,随后反复进行下列任意操作. ·从S的头部删除一个字符,加到T的尾部 ·从S的尾部删除一个字符,加到T的尾部 ...

  7. 【linux】 mail/mutt 发送邮件

    mail: 比较常用,缺点是发送附件要同时安装其他软件: mutt:功能强大,注意发送html需要升级到1.5+版本:   用mail发送邮件: echo "邮件正文" | mai ...

  8. 关于Python的10大实用编程技巧

      Python 是一种通用的脚本开发语言,比其他编程语言更加简单.易学,其面向对象特性甚至比Java.C#..NET更加彻底,因此非常适合快速开发. Python 已经成为最受欢迎的程序设计语言之一 ...

  9. Vue2.0响应式原理以及重写数组方法

    // 重写数组方法 let oldArrayPrototype = Array.prototype; let proto = Object.create(oldArrayPrototype); ['p ...

  10. c++ 由无向图构造邻接表,实现深度优先遍历、广度优先遍历。

    /* 首先,根据用户输入的顶点总数和边数,构造无向图,然后以用户输入的顶点 为起始点,进行深度优先.广度优先搜索遍历,并输出遍历的结果. */ #include <stdlib.h> #i ...