c++之判斷文件和路徑是否存在


簡介

  • 判斷文件/路徑是否存在
  • 新建文件/路徑

代碼

#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: 不能創建不存在目錄下的文件

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM