简体   繁体   中英

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?

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
}

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 dir ectory ent ries, ie 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.

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 .

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");
}

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

_mkdir("C:/folder")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM