Create directories in c ++ with Linux

1

I want to create a directory in the home folder with c ++, but there is no way to do this in a cross-platform way. I have found that in the "sys / stat.h" library has the mkdir function that creates directories, but in addition to the directory name, the function needs the directory permissions. so I made the code:

mkdir(nomedodiretorio.c_str(),0777);

It generates a folder, only it only allows me to write to myself and not to other users. I have already tried all variations of 0777 and it does not generate a folder with permissions from everything to all. What is the correct code?

    
asked by anonymous 22.05.2018 / 19:26

2 answers

2

From , 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 , 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);
}
    
22.05.2018 / 20:15
0

In

22.05.2018 / 22:40