Search code examples
c++windowsfiledirectorycopy

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.


Solution

  • 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()