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 appropr
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;
}
By default, Visual Studio #define
s _WIN32
in the preprocessor project settings.
So you can use
// _WIN32 = we're in windows
#ifdef _WIN32
// Windows
#else
// Not windows
#endif
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.
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)