【发布时间】:2013-12-03 18:06:33
【问题描述】:
有没有办法使用标准的 c 或 c++ 库来创建一个目录,包括给定绝对路径字符串可能需要的子文件夹?
谢谢
【问题讨论】:
标签: c++ c cross-platform
有没有办法使用标准的 c 或 c++ 库来创建一个目录,包括给定绝对路径字符串可能需要的子文件夹?
谢谢
【问题讨论】:
标签: c++ c cross-platform
是,在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>。
【讨论】:
使用标准库,你可以像在 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
}
【讨论】:
不,但如果你愿意使用 boost:
boost::filesystem::path dir("absolute_path");
boost::filesystem::create_directory(dir);
有一个proposal 可以将文件系统库添加到基于boost::filesystem 的标准库中。使用 boost::filesystem 和适当的 typedef 将使您处于有利位置,以便在您选择的编译器可用时迁移到未来的标准。
【讨论】: