Rakesh Malik
Rakesh Malik

Reputation: 689

Can't find mkdir() function in dirent.h for windows

I am using dirent.h 1.20 (source) for windows in VC2013.

I can't find mkdir() in it.

How am I supposed to use it? Or can I create a directory somehow only using dirent.h?

Upvotes: 7

Views: 29753

Answers (5)

DevSolar
DevSolar

Reputation: 70391

Update: Since C++17, <filesystem> is the portable way to go. For earlier compilers, check out Boost.Filesystem.


The header you are linking to is effectively turning your (POSIX) dirent.h calls into (native) Windows calls. But dirent.h is about directory entries, i.e. reading directories, not creating ones.

If you want to create a directory (mkdir()), you need either:

  • A similar wrapping header turning your (POSIX) mkdir() call into the corresponding (native) Windows function calls (and I cannot point out such a header for you), or
  • use the Windows API directly, which might be pragmatic but would lead to a really ugly mix of POSIX and Windows functions...

// UGLY - these two don't belong in the same source...
#include <dirent.h>
#include <windows.h>

// ...
CreateDirectory( "D:\\TestDir", NULL );
// ...

Another solution would be to take a look at Cygwin, which provides a POSIX environment running on Windows, including Bash shell, GCC compiler toolchain, and a complete collection of POSIX headers like dirent.h, sys/stat.h, sys/types.h etc., allowing you to use the POSIX API consistently in your programming.

Upvotes: 5

shawon
shawon

Reputation: 1022

mkdir is deprecated. Give #include <direct.h> as a header file. then write

_mkdir("C:/folder")

Upvotes: 0

user3960974
user3960974

Reputation:

You can use sys/types.h header file and use
mkdir(const char*) method to create a directory
Following is the sample code

#include<stdio.h>
#include<string.h>
#include <unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
int main()
{
    if(!mkdir("C:mydir"))
    {
        printf("File created\n");
    }
    else
        printf("Error\n");
}

Upvotes: 0

Rakesh Malik
Rakesh Malik

Reputation: 689

simplest way that helped without using any other library is.

#if defined _MSC_VER
#include <direct.h>
#elif defined __GNUC__
#include <sys/types.h>
#include <sys/stat.h>
#endif

void createDir(string dir) {
#if defined _MSC_VER
    _mkdir(dir.data());
#elif defined __GNUC__
    mkdir(dir.data(), 0777);
#endif
}

Upvotes: 16

crashmstr
crashmstr

Reputation: 28583

Visual Studio includes the <direct.h> header. This header declares _mkdir and _wmkdir, which can be used to create a directory, and are part of the C libraries included with Visual Studio.

The other "easy" option would be to use Windows API calls as indicated by DevSolar.

Upvotes: 2

Related Questions