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);
To check the operating system of the host in a C or C++ code, we need to check the macros defined by the compiler (GNU GCC or G++). For example, on Windows platform, the compiler has a special macro named _WIN32 defined. So, if the macro _WIN32 is defined, we are on Windows.
The answer is simple: There is no difference! However each operating system has its own API. This API does not depend on the programming language. Example: The "MessageBox()" function exists in Windows only, not in Linux.
Mobile. iOS, Android and Windows Phone kernels are also written in C. They are just mobile adaptations of existing Mac OS, Linux and Windows kernels. So smartphones you use every day are running on a C kernel.
C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around the early 1970s. The language was formalized in 1988 by the American National Standard Institute (ANSI). The UNIX OS was totally written in C.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With