Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 350
pourjour Avatar asked Feb 10 '12 22:02

pourjour


People also ask

How do you create a directory if it does not exist in Python?

import os path = '/Users/krunal/Desktop/code/database' os. makedirs(path, exist_ok=False) print("The new directory is created!") So that's how you easily create directories and subdirectories in Python with makedirs(). That's it for creating a directory if not exist in Python.

How do you create a directory if it doesn't exist in PowerShell?

PowerShell Create Directory If Not Exists using Test-Path If a path or directory is missing or doesn't exist, it will return $False. Using PowerShell New-Item cmdlet, it will create directory if not exists using Test-Path.

How do you create a directory if it does not exist in Java?

Create a Directory if it Does Not Exist You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.


2 Answers

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() 
like image 134
hmjd Avatar answered Sep 30 '22 08:09

hmjd


#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 } 
like image 25
Vertexwahn Avatar answered Sep 30 '22 09:09

Vertexwahn