跨平台创建目录的方式?

时间:2013-12-03 18:06:34

标签: c++ c

是否有办法使用标准c或c ++库创建目录,包括给定绝对路径字符串可能需要的子文件夹?

由于

3 个答案:

答案 0 :(得分:11)

使用标准库,你可以在C ++中这样做:

// ASSUMED INCLUDES
// #include <string> // required for std::string
// #include <sys/types.h> // required for stat.h
// #include <sys/stat.h> // no clue why required -- man pages say so

std::string sPath = "/tmp/test";
mode_t nMode = 0733; // UNIX style permissions
int nError = 0;
#if defined(_WIN32)
  nError = _mkdir(sPath.c_str()); // can be used on Windows
#else 
  nError = mkdir(sPath.c_str(),nMode); // can be used on non-Windows
#endif
if (nError != 0) {
  // handle your error here
}

答案 1 :(得分:7)

不,但是如果你愿意使用boost:

boost::filesystem::path dir("absolute_path");
boost::filesystem::create_directory(dir);

有一个proposal将文件系统库添加到标准库中,该库将基于boost::filesystem。使用boost::filesystem和适当的typedef将使您能够在可供您选择的编译器使用时迁移到将来的标准。

答案 2 :(得分:7)

,在 C ++ 17 中,您可以使用filesystem

#include <filesystem>
#if __cplusplus < 201703L // If the version of C++ is less than 17
    // It was still in the experimental:: namespace
    namespace fs = std::experimental::filesystem;
#else
    namespace fs = std::filesystem;
#endif
int main()
{
    // create multiple directories/sub-directories.
    fs::create_directories("SO/1/2/a"); 
    // create only one directory.
    fs::create_directory("SO/1/2/b");
    // remove the directory "SO/1/2/a".
    fs::remove("SO/1/2/a");
    // remove "SO/2" with all its sub-directories.
    fs::remove_all("SO/2");
}

注意仅使用正斜杠/可能需要包含<experimental/filesystem>