boost::filesystem 建立資料夾

本篇介紹使用 boost C++ 的 filesystem 模組來建立資料夾。

幾年前為了寫 C++ 跨平台程式,研究了一下怎麼用 boost 的 filesystem 模組來完成這個功能,最近在整理 boost 的筆記就順便記錄下來吧!
這個功能最新的 C++17 也已經加入這個功能了,相信再過幾年就很普及了。

安裝 boost

還沒安裝 boost 的話請參考 windows 安裝方式 / ubuntu 安裝方式

使用範例

可以一次建立多層資料夾目錄

boost-filesystem-create-directory.cpp
1
2
3
4
5
6
7
8
9
10
11
12
// g++ boost-filesystem-create-directory.cpp -o a.out -lboost_filesystem
#include <iostream>
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

int main(int argc, const char *argv[])
{
create_directories("image/out");
return 0;
}

編譯

在 linux 下使用 g++ 編譯需要連結 boost_filesystem 函式庫

1
$ g++ boost-filesystem-create-directory.cpp -o a.out -lboost_filesystem

參考
[1] Filesystem Tutorial 1.47.0
http://www.boost.org/doc/libs/1_47_0/libs/filesystem/v3/doc/tutorial.html
[2] Filesystem Tutorial 1.66.0
https://www.boost.org/doc/libs/1_66_0/libs/filesystem/doc/tutorial.html
[3] C++ 檔案、資料夾、路徑處理函式庫:boost::filesystem
https://kheresy.wordpress.com/2010/10/25/boost_filesystem/