跨平台创建包括子文件夹的目录的方法?

19

使用标准的C或C++库是否有一种方法可以创建一个目录,包括给定绝对路径字符串所需的子文件夹?

谢谢


https://dev59.com/a6Dha4cB1Zd3GeqP_Cnx - Bernardo Ramos
3个回答

19

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


#if __cplusplus < 201703L // If the version of C++ is less than 17
#include <experimental/filesystem>
    // It was still in the experimental:: namespace
    namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
    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>


12

使用标准库,在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
好像它不会为Windows创建子文件夹。 - Sergei Krivonos

10
不,但如果你愿意使用boost:
boost::filesystem::path dir("absolute_path");
boost::filesystem::create_directory(dir);

有一个proposal,即向标准库中添加一个基于boost::filesystem的文件系统库。使用boost::filesystem和适当的typedef将使您处于良好的位置,以便在未来标准可用于您选择的编译器时进行迁移。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接