如何查找文件夹是否存在以及如何创建文件夹

How to find out if a folder exists and how to create a folder?

本文关键字:文件夹 何创建 创建 存在 何查找 是否 查找      更新时间:2023-10-16

我试图创建一个文件夹,如果它不存在。我正在使用Windows,我对我的代码在其他平台上工作不感兴趣。

没关系,我找到解决办法了。我只是有包容问题。答案是:
#include <io.h>   // For access().
#include <sys/types.h>  // For stat().
#include <sys/stat.h>   // For stat().
#include <iostream>
#include <string>
using namespace std;
string strPath;
   cout << "Enter directory to check: ";
   cin >> strPath;
   if ( access( strPath.c_str(), 0 ) == 0 )
   {
      struct stat status;
      stat( strPath.c_str(), &status );
      if ( status.st_mode & S_IFDIR )
      {
         cout << "The directory exists." << endl;
      }
      else
      {
         cout << "The path you entered is a file." << endl;
      }
   }
   else
   {
      cout << "Path doesn't exist." << endl;
   }

posix兼容的调用是mkdir。当目录已经存在时,它会静默失败。

如果您使用的是Windows API,那么CreateDirectory更合适。

使用boost::filesystem::exists检查文件是否存在

boost::filesystem::create_directories就是这样做的:给它一个路径,它将在该路径中创建所有缺失的目录。