Creating and Deleting Directories in C++

1. Description

  1. If the compiler supports C++17, it is recommended to use the <span>std::filesystem</span> related functions
  2. If used only on Windows platform, you can use <span>_mkdir</span> and <span>_rmdir</span>
  3. If used only on Linux platform, you can use <span>mkdir</span> and <span>rmdir</span>
  4. If the code needs to be cross-platform, you can use system calls to unify
  5. If you are using the QT library, you can leverage QT’s operations for unification
  6. Some functions will fail if the directory already exists when trying to create it
  7. Some functions can only delete empty directories

2. Using C++17 std::filesystem related functions

#include <filesystem>
std::string directory_name("folder_name");
std::filesystem::create_directory(directory_name);

std::filesystem::remove("folder_name");     // Deletes empty directories or single files.
std::filesystem::remove_all("folder_name"); // Deletes one or more files recursively.

3. Windows Platform <span>_mkdir</span><span>_rmdir</span>

#include <direct.h>

string folderPath = "folder_name"; 
_mkdir(folderPath.c_str());   // Returns 0 indicates success, -1 indicates failure

_rmdir(folderPath.c_str());   // Returns 0 indicates success, -1 indicates failure

mkdir will raise a deprecated function warning, so use _mkdir

Windows also has another way

#include <windows.h>

if (CreateDirectory("folder_name", NULL)) {
    // Directory created
}
else if (ERROR_ALREADY_EXISTS == GetLastError()) {
    // Directory already exists
}
else {
    // Failed for some other reason
}

RemoveDirectory("folder_name");

4. Linux Platform <span>mkdir</span><span>rmdir</span>

#include <sys/stat.h>

const int dir_err = mkdir("folder_name", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (-1 == dir_err)
{
    printf("Error creating directory!\n");
    exit(1);
}

int status = rmdir("folder_name");

https://pubs.opengroup.org/onlinepubs/009696699/functions/mkdir.htmlhttps://linux.die.net/man/3/rmdir

5. Using System Calls

#include <stdlib.h>

system("mkdir folder_name");

system("rmdir folder_name");

Creating multi-level directories

int create_multi_level_directories(std::string folder)
{
    std::replace(folder.begin(), folder.end(), '/', '\');

#ifdef _WIN32
    std::string command = "mkdir " + folder;
#elif __linux__
    std::string command = "mkdir -p " + folder;
#else
    #error "Unknown compiler"
    return -1;
#endif

     int status = system(command.c_str());

    if (0 != status) {
        printf("create %s failed\n", folder.c_str());
        return status;
    }

    return 0;
}

6. QT Directory Operations

#include <QDir>
#include <QString>

// create result directory;
result_directory_path = QDir::currentPath().toStdString() + "/folder_name";
QString result_path = QString::fromStdString(result_directory_path);
QDir qdir;
bool doesResultDirExist = qdir.exists(result_path);
if (false == doesResultDirExist) {
    doesResultDirExist = qdir.mkpath(result_path);
    if (false == doesResultDirExist) {
        PRINTF_ERROR("create result directory(%s) failed", result_directory_path.c_str());
    }
}

7. Others – Converting Path Separators from “\” to “/”

#include <algorithm>

std::replace(result_directory_path.begin(), result_directory_path.end(), '\', '/');

Leave a Comment