16

I'm trying to create a folder if it doesn't exist. I'm using Windows and I am not interested on my code working in other platforms.

Never mind, I found the solution. I was just having a inclusion problem. The answer is:

#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;
   }
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Sara
  • 833
  • 2
  • 9
  • 21

3 Answers3

13

The POSIX-compatible call is mkdir. It silently fails when the directory already exists.

If you are using the Windows API, then CreateDirectory is more appropriate.

Andy Finkenstadt
  • 3,547
  • 1
  • 21
  • 25
13

Use boost::filesystem::exists to check if file exists.

Alexey Malistov
  • 26,407
  • 13
  • 68
  • 88
12

boost::filesystem::create_directories does just that: Give it a path, and it will create all missing directories in that path.

Mephane
  • 1,984
  • 11
  • 18
  • Searching on Google for `boost check directory exists then create C++` brought me here as the first search result. Thanks. +1. – rayryeng Jul 08 '17 at 01:05