我正在用C++编写跨平台兼容的函数,该函数根据输入文件名创建目录。我需要知道机器是Linux还是Windows,并使用适当的正斜杠或反斜杠。对于下面的以下代码,如果计算机是Linux,则为isLinux = true。如何确定操作系统?

bool isLinux;
std::string slash;
std::string directoryName;

if isLinux
   slash = "/";
else
   slash = "\\";
end

boost::filesystem::create_directory (full_path.native_directory_string() + slash + directoryName);

最佳答案

使用:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
static const std::string slash="\\";
#else
static const std::string slash="/";
#endif

顺便说一句,您仍然可以在Windows上安全地使用此斜杠“/”,因为Windows可以很好地理解这一点。因此,仅使用“/”斜杠就可以解决所有操作系统的问题,即使OpenVMS的路径为foo:[bar.bee]test.ext也可以表示为/foo/bar/bee/test.ext

09-06 22:12