Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

c++ - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:estEmploi Nam.docx": there is a missing path separator between the directory and the filename. Example fix:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...