Search code examples
c++create-directory

How do I create a directory without using wide strings in C++?


I'm trying to create a directory so that I can put a file into it.

My code:

string Set;
...
CreateDirectory("Game/Sets/" + Set, NULL); // I'm trying to have something like this. CreateDirectory needs wide strings, but Set is narrow.

The variable Set is a narrow string.

I think I might need something other than CreateDirectory, but I don't know what.


Solution

  • You have to use the string::c_str() member function to get the corresponding const char* (AKA LPCSTR):

    string Set;
    ...
    CreateDirectory(("Game/Sets/" + Set).c_str(), NULL);
    

    But it is probably better to use a temporary variable:

    string Set;
    ...
    string fullDir = "Game/Sets/" + Set;
    CreateDirectory(fullDir.c_str(), NULL);
    

    It can happen that you are compiling a UNICODE program. If that is the case, you will get an error because const char* is not convertible to const wchar_t*. The solution is to call the ANSI version of the function:

    CreateDirectoryA(fullDir.c_str(), NULL);
    

    If you prefer you can use the ANSI function even if there is no error, just to be extra consistent.

    Remember that CreateDirectory is actually a macro that expands to CreateDirectoryW or CreateDirectoryA depending on the project configuration. You can use any one of these three names as you see fit.