c++之判斷檔案和路徑是否存在
阿新 • • 發佈:2021-06-26
目錄
簡介
- 判斷檔案/路徑是否存在
- 新建檔案/路徑
程式碼
#include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> bool isDirExist(const std::string& path_name) { if (boost::filesystem::exists(path_name) && boost::filesystem::is_directory(path_name)) { return true; } return false; } bool createNewDir(const std::string& path_name) { if (isDirExist(path_name)) { return true; } return boost::filesystem::create_directories(path_name); } bool isFileExist(const std::string& file_name) { if (boost::filesystem::exists(file_name) && boost::filesystem::is_regular_file(file_name)) { return true; } return false; } bool createNewFile(const std::string& file_name) { if (isFileExist(file_name)) { return true; } boost::filesystem::ofstream file(file_name); file.close(); return isFileExist(file_name); }
筆記
-
由於
boost::filesystem::exists(test_dir)
該函式不區分資料夾還是檔案,因此區分需要配合另外函式 -
路徑是否存在:
boost::filesystem::exists(path_name)
+boost::filesystem::is_directory(path_name)
-
檔案是否存在:
boost::filesystem::exists(file_name)
+boost::filesystem::is_regular_file(file_name)
-
建立目錄:
create_directories
: 可以建立多級目錄 -
建立檔案:
boost::filesystem::ofstream