Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

directory

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;
   }
like image 746
Sara Avatar asked Apr 11 '11 13:04

Sara


People also ask

How to check if folder exists in a file path?

Check if a folder exists in a file path, if not, to create it under this specific file path, the following VBA code may help you to finish this job. 1. Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window. 2. Click Insert > Module, and paste the following code in the Module Window.

How to create a folder dynamically if it doesn't exist?

If it doesn't exists then it has to create new folder and then copy that file there. Note: If there needs to be a sub folder, then it has to create that subfolder. Overall, it needs to create folder dynamically whether it is an root folder or sub folder or several layers of folder.

How to check if a file is a directory or not?

To explicitly make sure it's a directory and not a file, use the -PathType parameter which accepts the following values: In a script, you would typically use it in an if statement. To negate and check if the folder or file does not exist, use either "!"

How do I check if a file exists in boost?

Use boost::filesystem::exists to check if file exists. boost::filesystem::create_directories does just that: Give it a path, and it will create all missing directories in that path. Searching on Google for boost check directory exists then create C++ brought me here as the first search result. Thanks. +1.


Video Answer


1 Answers

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.

like image 128
Andy Finkenstadt Avatar answered Sep 19 '22 09:09

Andy Finkenstadt