c++create-directory

The expression must have a class type


I am currently programming a patching application for my game. As i am used to program with Java its hard for me to get along with C++, the patcher has to be wridden in C++ unfortunately, in Java i could do this in 5 minutes but a new language. . . not so much.

This is my current Code to create the folders i need:

#include <windows.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    //Set the Strings the Patcher needs.
    string DNGDirectory = "C:\\dnGames";
    const char* DDDirectory = "C:\\dnGames\\DuelistsDance";

    //Create directories if they don't exist yet.
    if (CreateDirectory(DNGDirectory.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError())
    {
        if (CreateDirectory(DDDirectory.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError())
        {
            cout << "Directories successfully created." << std::endl;
        }
    }

    return 0;
}

One time i use string for the variable, because this was in the example code i picked out from Google (Create a directory if it doesn't exist), but i get the error "Das Argument vom Typ ""const char "" ist mit dem Parameter vom Typ ""LPCWSTR"" inkompatibel." (Should be the argument of type ""const char" is incompatible with the parameter of type ""LPCWSTR"" in english) I tried to fix it by using "const char*" as type, but this gets me the error "Der Ausdruck muss einen Klassentyp aufweisen." (They expression must have a class type). Does anyone know how to fix this? I am using Visual Studio 2019 for this.


Solution

  • Since C++17 (and to a lesser extent 14) we can use std::filesystem (std::experimental::filesystem in C++14) to manipulate files and create directories.

    For example in your case:

    ...
    std::filesystem::path DDDirectory("C:\\dnGames\\DuelistsDance"); 
    
    try {
      std::filesystem::create_directories(DDDirectory); // Creates all the directories needed, like mkdir -p on linux
    
    // Success here
    
    } catch(std::filesystem::filesystem_error& e) {
      // Handle errors here
    }
    

    This will make handling of your errors cleaner and your code cross-platform (although you will have to change the path, but std::filesystem::path turns / into \\ on windows anyway). It also makes your code easier to read and as you can see, much much shorter.