From c ++ 17 , it is possible to perform file system operations in a portable / cross-platform manner, using the library <filesystem>
:
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path nome_do_diretório = "exemplo1";
fs::create_directory(nome_do_diretório);
}
If you want to create directories recursively (eg exemplo/de/dir/recursivo
), use std::filesystem::create_directories
.
If you do not have access to c ++ 17 , you can use the Boost Equivalent Library (almost all the API is equivalent to the one introduced in C ++, so it is possible to change implementation without practically changing the code.)
A better way to pass the correct permissions to the new directory is to use the permissions of the existing directory where the new one will be created. To do this, pass the directory whose permissions will be copied as the second argument:
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path novo_dir = "exemplo1";
fs::path existente_dir = ".";
fs::create_directory(novo_dir, existente_dir);
}
On Linux, the copy of permissions is equivalent to the following code:
#include <filesystem>
#include <sys/stat.h>
namespace fs = std::filesystem;
int main()
{
fs::path novo_dir = "exemplo1";
fs::path existente_dir = ".";
struct stat atributos;
stat(existente_dir.c_str(), &atributos);
mkdir(novo_dir.c_str(), atributos.st_mode);
}