c++ - 在 C++ 中确定是 Linux 还是 Windows

标签 c++ windows linux cross-platform

我正在用 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/

相关文章:

windows - 在没有管理员权限的情况下更改注册表

linux - Moodle 2.5 (openSuse) cron 作业停止运行,我找不到它,或日志,Moodle 的 cron 在哪里?

c - 在这个特定场景中,内联代码放在哪里?

c++ - 在具有 1GB RAM 的机器上对 1TB 文件进行排序

c++ - 可变参数模板递归类型传递

java - 基于终端的角色扮演游戏

linux - 通过 SSH 和私钥连接到 MySQL

c++ - 执行 RSA 解密时密文无效

c - 哪个更适合windows? pthreads 还是 CreateMutex?

windows - 如何在 Windows 的 sublime text 3 中设置 Gosublime?