boost Filesystem

本文深入讲解了Boost.Filesystem库的功能,包括路径操作、文件和目录的处理、异常处理及迭代器使用等。通过实例演示了如何创建、读取、修改和删除文件与目录。

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 0;
}

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 0;
}

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 0;
}

 

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 0;
}

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 0;
}

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 0;
}

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.

转载于:https://www.cnblogs.com/sssblog/p/11293873.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值