如何确定文件夹是否存在以及如何创建文件夹?

Sar*_*ara 15 c++ directory

我正在尝试创建一个文件夹,如果它不存在.我正在使用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;
   }
Run Code Online (Sandbox Code Playgroud)

Ale*_*tov 13

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


And*_*adt 12

与POSIX兼容的呼叫是mkdir. 当目录已存在时,它会静默失败.

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


Mep*_*ane 11

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