From c++17, it is possible to perform operations with the file system in a portable/cross-platform way, 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 (e. g. exemplo/de/dir/recursivo
), use std::filesystem::create_directories
.
If you don’t have access to c++17, you can use the Boost equivalent library (almost the entire API is equivalent to the one introduced in C++, so it is possible to change the 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);
}
Attention that
0777
is interpreted as octal and actually corresponds to the number511
decimally. Have you seen the permissions parameters in documentation ?– Isac