簡介
- 判斷文件/路徑是否存在
- 新建文件/路徑
代碼
#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
: 不能創建不存在目錄下的文件