Boost_file_system

1
2
#include < boost/filesystem.hpp>  
using namespace boost::filesystem;
  1. file name operation

    1
    2
    3
    4
    5
    6
    7
    8
    9
    //Note the difference between /= and +=, /= means appending directory, += means string concatenation 
    path dir("C:\\Windows");
    dir /= "System32";
    dir /= "services.exe";
    std::cout << dir.string() << std::endl;
    std::cout << dir.parent_path()<< std::endl; /C:\Windows\System32
    std::cout << dir.filename()<< std::endl; /services.exe
    std::cout << dir.stem()<< std::endl; //services
    std::cout << dir.extension()<< std::endl; //.exe
  2. file operation: rename, remove, copy

    1
    2
    3
    4
    5
    6
    7
    8
    9
    exists(path);                               
    is_directory(path);
    is_regular_file(path);

    remove_all(const Path& p); //remove all files recursively
    rename(const Path1& from_p, const Path2& to_p);
    copy_file(const Path1& from_fp, const Path2& to_fp);
    create_directory(const Path & p);
    create_directories(const Path & p); //make directory recursively</pre>
  3. shallow visit directory

    1
    2
    3
    4
    5
    6
    path dir2("c:\\Windows\\System32");
    directory_iterator end;
    for (directory_iterator pos(dir2); pos != end; pos++)
    {
    std::cout << *pos << std::endl;
    }
  4. deep visit directory: like DFS, stack push&&pop

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    typedef recursive_directory_iterator rd_iterator;
    path dir2("E:\\Student");
    rd_iterator end;
    for (rd_iterator pos(dir); pos != end; pos++)
    {
    if (is_directory(*pos) && pos.level() > 4)
    {
    pos.no_push();
    }
    if (*pos == "nofind.txt")
    {
    pos.pop();
    }
    else
    {
    cout<< pos->path().filename().string()<< endl;
    }
    }
  5. catch error

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    try
    {
    path dir2("c:\\Windows\\System32");
    assert(is_directory(dir2));
    assert(exists(dir2));
    }
    catch(filesystem_error& e)
    {
    std::cout << e.path1() << std::endl;
    std::cout << e.what() << std::endl;
    }