- filesystem庫提供了兩個頭文件,一個是<boost/filesystem.hpp>,這個頭文件包括基本的庫內容。它提供了對文件系統的重要操作。
同一時候它定義了一個類path。正如大家所想的。這個是一個可移植的路徑表示方法,它是filesystem庫的基礎。
- 一個是<boost/filesystem/fstream.hpp>。是對std::fstream的一個補充,使用能夠使用類boost::path作爲參數。從而使得filesystem庫與標準庫的關係更親熱。
- 由於文件系統對於大多數系統來說都是共享的,所以不同的進程能夠同一時候操作同一個對象,因此filesysetm不提供這方面的特性保證。
當然這樣的保證也是不可能的。或者至少昂貴的。
- filesystem在不論什麼時候,僅僅要不能完畢對應的任務。它都可能拋出 basic_filesystem_error異常。當然並不是總會拋出異常。由於在庫編譯的時候能夠關閉這個功能。同一時候有兩個函數提供了無異常版本號。這是由於在任務不能完畢時並不是是異常。
- filesystem庫的全部內容定義在boost名字空間的一個下級名字空間裏,它叫boost::filesytem。在使用boost.filesytem之後,鏈接時須要加“-lboost_filesystem-mt”選項,由於這個須要額外的鏈接,並不是一個純頭文件的庫。
- 本文中所用boost庫爲1_54
#include<boost/filesystem.hpp> { boost::filesystem::path path("/test/test1"); //初始化 boost::filesystem::path old_cpath = boost::filesystem::current_path(); //取得當前程序所在文件夾 boost::filesystem::path parent_path = old_cpath.parent_path();//取old_cpath的上一層父文件夾路徑 boost::filesystem::path file_path = old_cpath / "file"; //path支持重載/運算符 if(boost::filesystem::exists(file_path)) //推斷文件存在性 { std::string strPath = file_path.string(); int x = 1; } else { //文件夾不存在; boost::filesystem::create_directory(file_path); //文件夾不存在。創建 } bool bIsDirectory = boost::filesystem::is_directory(file_path); //推斷file_path是否爲文件夾 boost::filesystem::recursive_directory_iterator beg_iter(file_path); boost::filesystem::recursive_directory_iterator end_iter; for (; beg_iter != end_iter; ++beg_iter) { if (boost::filesystem::is_directory(*beg_iter)) { continue; } else { std::string strPath = beg_iter->path().string(); //遍歷出來的文件名稱 int x=1; } } boost::filesystem::path new_file_path = file_path / "test.txt"; if(boost::filesystem::is_regular_file(new_file_path)) //推斷是否爲普通文件 { UINT sizefile = boost::filesystem::file_size(new_file_path); //文件大小(字節) int x =1; } boost::filesystem::remove(new_file_path);//刪除文件new_file_path }
//根據文件夾路徑創建文件
-
bool MakeFullPathDir(const string& path) { if (path.empty()) { return false; } size_t uPos = path.find_first_of("/\\"); while (uPos != string::npos) { string dir = path.substr(0, uPos + 1); boost::system::error_code ec; boost::filesystem::create_directory(dir, ec); uPos = path.find_first_of("/\\", uPos + 1); } boost::system::error_code ec; boost::filesystem::create_directory(path, ec); return true; }
boost::filesystem使用方法,根據路徑創建文件夾
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.