确定C++中的Linux或Windows

Elp*_*rto 22 c++ linux windows 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); 
Run Code Online (Sandbox Code Playgroud)

Art*_*yom 41

使用:

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

顺便说一句,你仍然可以安全地在Windows上使用这个斜杠"/",因为Windows完全理解这一点.因此,只需坚持使用"/"斜杠即可解决所有操作系统的问题,即使OpenVMS foo:[bar.bee]test.ext也可以表示为路径/foo/bar/bee/test.ext.

  • 有一些Win32函数不喜欢不正确的Win32目录分隔符"/".但是,如果您使用Win32功能,那么您可能已经知道您的目标是Windows. (5认同)
  • 通过"少数"我的意思是"少数"...... :)我认为其中一些是敏感的:http://msdn.microsoft.com/en-us/library/bb773559(VS.85).aspx此外,这里有一个明确的警告:http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx.尽管如此,我反对正斜杠的主要原因是,当我在Microsoft Windows路径中看到其中一个时,它会伤到我的眼睛...... (4认同)

Bil*_*eal 13

一般来说,你可以通过条件编译来做到这一点.

也就是说,如果您正在使用,则boost::filesystem应该使用便携式通用路径格式,以便您可以忘记这样的事情.


bob*_*obo 6

默认情况下,Visual Studio中#defineŞ_WIN32预处理器中的项目设置。

所以你可以使用

// _WIN32 = we're in windows
#ifdef _WIN32
// Windows
#else
// Not windows
#endif
Run Code Online (Sandbox Code Playgroud)