mkdir Windows vs Linux
26,012
Solution 1
#if defined(_WIN32)
_mkdir(strPath.c_str());
#else
mkdir(strPath.c_str(), 0777); // notice that 777 is different than 0777
#endif
Solution 2
You should be able to use conditional compilation to use the version that applies to the OS you are compiling for.
Also, are you really sure you want to set the flags to 777 (as in wide open, please deposit your virus here)?
Solution 3
You can conditionally compile with some preprocessor directives, a pretty complete list of which you can find here: C/C++ Compiler Predefined Macros
#if defined(_WIN32)
_mkdir(strPath.c_str());
#elif defined(__linux__)
mkdir(strPath.c_str(), 0777);
// #else more?
#endif
Author by
MindlessMaik
Updated on April 14, 2020Comments
-
MindlessMaik about 4 years
I have a problem while porting a Linux tool to Windows. I am using MinGW on a Windows system. I have a class which handles all the in/output and within is this line:
mkdir(strPath.c_str(), 0777); // works on Linux but not on Windows and when it is changed to _mkdir(strPath.c_str()); // it works on Windows but not on Linux
Any ideas what I can do, so that it works on both systems?
-
wkl about 12 years@EricJ. -
_WIN32
is defined in 64-bit windows as well. -
heroddaji almost 12 years"_WIN32 - Defined for applications for Win32 and Win64". (ref: msdn.microsoft.com/en-us/library/b0084kay.aspx) Therefore the check for _WIN64 is not necessary here.
-
gcochard almost 12 yearsFor reference, that's a great thing to know. Short circuit evaluation makes it moot in this case though.
-
jw013 over 11 yearsShouldn't that be
#if defined(_WIN32) || defined(_WIN64)
to be valid? There's no such thing as#ifdef foo || bar
- it's not valid preprocessor syntax as far as I know. -
gcochard over 11 years@jw013
#ifdef
is valid in both gnu c++ and the visual studio compilers. See gcc.gnu.org/onlinedocs/cpp/Ifdef.html, msdn.microsoft.com/en-us/library/t22e924w(v=vs.80).aspx, and stackoverflow.com/a/3803108/1355166 for more info. -
jw013 over 11 years@Greg You misunderstood.
#ifdef constant_name
is valid.#ifdef foo || bar
is not.#ifdef
doesn't take expressions. What compiler do you use that accepts such syntax? -
gcochard over 11 years@jw013 I would say it's valid in visual studio, but now that I'm thinking about it, you're probably right. I will edit the answer with this in mind.
-
Agostino about 9 years
_mkdir
is included withdirect.h
in Visual Studio, and does not exist in GCC. You may want to add#ifdef _MSC_VER
#include <direct.h>
#endif
-
Jon about 9 yearsLive dangerously! ;)