pourjour
pourjour

Reputation: 1216

Create a directory if it doesn't exist

In my app I want to copy a file to the other hard disk so this is my code:

 #include <windows.h>

using namespace std;

int main(int argc, char* argv[] )
{
    string Input = "C:\\Emploi NAm.docx";
    string CopiedFile = "Emploi NAm.docx";
    string OutputFolder = "D:\\test";
    CopyFile(Input.c_str(), string(OutputFolder+CopiedFile).c_str(), TRUE);

    return 0;
}

so after executing this, it shows me in the D:HDD a file testEmploi NAm.docx but I want him to create the test folder if it doesn't exist.

I want to do that without using the Boost library.

Upvotes: 91

Views: 270055

Answers (10)

Eike
Eike

Reputation: 409

Since c++17, you can easily do this cross-platform with:

#include <filesystem>
int main() {
bool created_new_directory = false;
bool there_was_an_exception = false;

try {
  created_new_directory
      = std::filesystem::create_directory("directory_name");
} catch(std::exception & e){
there_was_an_exception = true;
// creation failed
}
if ((not created_new_directory) and (not there_was_an_exception)) {
    // no failure, but the directory was already present.
  }
}

Note, that this version is very useful, if you need to know, whether the directory is actually newly created. And I find the documentation on cppreference slightly difficult to understand on this point: If the directory is already present, this function returns false.

This means, you can more or less atomically create a new directory with this method.

Upvotes: 10

driedler
driedler

Reputation: 4190

This works in GCC:

Taken from: Creating a new directory in C

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

Upvotes: 5

Vertexwahn
Vertexwahn

Reputation: 8170

#include <experimental/filesystem> // or #include <filesystem> for C++17 and up
    
namespace fs = std::experimental::filesystem;


if (!fs::is_directory("src") || !fs::exists("src")) { // Check if src folder exists
    fs::create_directory("src"); // create src folder
}

Upvotes: 73

saurabheights
saurabheights

Reputation: 4574

OpenCV Specific

Opencv supports filesystem, probably through its dependency Boost.

#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);

Upvotes: 6

Chris Rayner
Chris Rayner

Reputation: 437

Probably the easiest and most efficient way is to use boost and the boost::filesystem functions. This way you can build a directory simply and ensure that it is platform independent.

const char* path = _filePath.c_str();
boost::filesystem::path dir(path);
if(boost::filesystem::create_directory(dir))
{
    std::cerr<< "Directory Created: "<<_filePath<<std::endl;
}

boost::filesystem::create_directory - documentation

Upvotes: 42

Noa Yehezkel
Noa Yehezkel

Reputation: 508

You can use cstdlib

Although- http://www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>

const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}

you can also check if the directory exists already by using

#include <dirent.h>

Upvotes: 2

DotNetUser
DotNetUser

Reputation: 6612

Use CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

If the function succeeds it returns non-zero otherwise NULL.

Upvotes: 3

jiasli
jiasli

Reputation: 9148

_mkdir will also do the job.

_mkdir("D:\\test");

https://msdn.microsoft.com/en-us/library/2fkk4dzw.aspx

Upvotes: 10

Fivee Arch
Fivee Arch

Reputation: 294

Here is the simple way to create a folder.......

#include <windows.h>
#include <stdio.h>

void CreateFolder(const char * path)
{   
    if(!CreateDirectory(path ,NULL))
    {
        return;
    }
}


CreateFolder("C:\\folder_name\\")

This above code works well for me.

Upvotes: 21

hmjd
hmjd

Reputation: 122011

Use the WINAPI CreateDirectory() function to create a folder.

You can use this function without checking if the directory already exists as it will fail but GetLastError() will return ERROR_ALREADY_EXISTS:

if (CreateDirectory(OutputFolder.c_str(), NULL) ||
    ERROR_ALREADY_EXISTS == GetLastError())
{
    // CopyFile(...)
}
else
{
     // Failed to create directory.
}

The code for constructing the target file is incorrect:

string(OutputFolder+CopiedFile).c_str()

this would produce "D:\testEmploi Nam.docx": there is a missing path separator between the directory and the filename. Example fix:

string(OutputFolder+"\\"+CopiedFile).c_str()

Upvotes: 89

Related Questions