问题描述
我在C ++中编写了一个基于输入文件名创建目录的跨平台兼容函数。我需要知道,如果机器是Linux或Windows和使用适当的前进或反斜线。对于下面的代码,如果机器是Linux,则 isLinux = true
。如何确定操作系统?
I am writing a cross-platform compatible function in C++ that creates directories based on input filenames. I need to know if the machine is Linux or windows and use the appropriate forward or back slash. For the following code below, if the machine is Linux then isLinux = true
. How do I determine the OS?
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
BTW,您仍然可以安全地在Windows上使用这个斜杠/ windows完全理解这一点。因此,只要坚持使用/斜杠就可以解决所有操作系统的问题,即使像OpenVMS,路径 foo:[bar.bee] test.ext
可以表示为 /foo/bar/bee/test.ext
。
BTW, you can still safely use this slash "/" on Windows as windows understands this perfectly. So just sticking with "/" slash would solve problems for all OSes even like OpenVMS where path is foo:[bar.bee]test.ext
can be represented as /foo/bar/bee/test.ext
.
这篇关于确定Linux或Windows在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!