Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Linux or Windows in C++

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);  
like image 521
Elpezmuerto Avatar asked Jul 09 '10 13:07

Elpezmuerto


People also ask

How do I know what operating system I am running C++?

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.

Is C in Linux different from 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.

Does C only run on 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.

What is operating system in C program?

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.


1 Answers

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.

like image 84
Artyom Avatar answered Oct 13 '22 04:10

Artyom