boost::filesystem 常用命令集合

  • 命名空間聲明 & 引用頭文件聲明:使用fs來簡化操作
#include <boost/filesystem.hpp>
#include <iostream>  
namespace fs = boost::filesystem;
  • 定義path
std::string dir="C:\\Folder1\\Folder2";
fs::path path(dir);
  • 判斷path是否爲空
if (!fs::exists(path)) {return -1;}
  • boost::filesystem::path轉爲std::string
std::string str=path.string();
  • 創建新的目錄;
std::string new_path="C:\\Folder1\\NewFolder2";
fs::create_directory(new_path);
  • 創建目錄指針,並用來判斷獲取類型是文件還是文件夾
fs::directory_iterator iter(path);
if (fs::is_directory(iter->status()))
{//判斷是否爲目錄文件}
if (fs::is_regular_file(iter->status()))
{//判斷是否爲普通文件}
  • 獲取文件的類型名、文件名、上層文件夾及名稱;
std::string file="C:\\Folder1\\Folder2\\file.txt";
fs::path path(file);\\定義path
if (p.extension().compare(".jpg") == 0)
{return true; }//獲取類型名".txt",並與".jpg"進行比較
fs::path fileName=path.stem();//文件名稱"file"
fs::path parentPath=path.parent_path();//獲取上層文件目錄"C:\\Folder1\\Folder2"
std::string folderName=(path.parent_path()).string();//獲取文件夾目錄Folder2
  • 文件及文件夾名稱合成
std::string in_file="C:\\file.jpg";//輸入文件的路徑
std::string out_dir="D:\\folder1\\folder2\\";//輸出文件的目錄
fs::path in_path(in_file);
fs::path out_path(out_dir);//"D:\\folder1\\folder2\\"
if(!fs::exist(out_path))
{ fs::create_directory(out_path);}//如果文件不存在,則新建之
out_path/=in_path.stem();//提取輸入文件名 file,添加到路徑後面"D:\\folder1\\folder2\\file"
std::string output_str=out_path.string()+".bmp";//輸出"D:\\folder1\\folder2\\file.bmp"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章