开发者

Determine if Linux or Windows in C++

开发者 https://www.devze.com 2023-01-06 10:06 出处:网络
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 sl

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); 


Use:

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

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.


Generally speaking, you'd have do do this with conditional compilation.

That said, if you're using boost::filesystem you should be using the portable generic path format so that you can forget about things like this.


By default, Visual Studio #defines _WIN32 in the preprocessor project settings.

So you can use

// _WIN32 = we're in windows
#ifdef _WIN32
// Windows
#else
// Not windows
#endif


Look into http://en.wikipedia.org/wiki/Uname

If you are using g++ as your compiler/GNU then you could try the code below. POSIX compliant environments support this:

#include <stdio.h>
#include <sys/utsname.h>
#include <stdlib.h>

int main()
{
    struct utsname sysinfo;
    if(uname(&sysinfo)) exit(9);
    printf("os name: %s\n", sysinfo.sysname);
    return 0;
}


One of the most used methods to do this is with a pre-processor directive. The link is for C but they're used the same way in C++. Fair warning, each compiler & OS can have their own set of directives.


predef.sourceforge.net is a comprehensive collection of all kinds of MACROs that identify compilers/operating systems and more. (linking directly to the operating system sub-site)

0

精彩评论

暂无评论...
验证码 换一张
取 消