我正在用 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
。
关于c++ - 在 C++ 中确定是 Linux 还是 Windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3213037/