Mkdir c ++ function

I need to use the mkdir C ++ function in VS 2008, which takes two arguments and is deprecated from VS 2005.

However, this function is used in our code, and I need to write a separate product (containing only the mkdir function) to debug something.

What header files do I need to import? I used direct.h, however the compiler complains that the argument does not accept 2 arguments (the reason is that the function was deprecated in VS 2005).

mkdir("C:\hello",0); 
+7
source share
4 answers

If you want to write cross-platform code, you can use boost::filesystem routines

 #include <boost/filesystem.hpp> boost::filesystem::create_directory("dirname"); 

This adds a library dependency, but most likely you are going to use other file system routines, and boost::filesystem has some excellent interfaces for this.

If you only need to create a new directory, and if you intend to use VS 2008, you can use _mkdir() , as others have noted.

+12
source

It is deprecated, but it has been replaced by ISO C ++ _mkdir() , so use this version. All you need to name is the name of the directory, its only argument:

 #include <direct.h> void foo() { _mkdir("C:\\hello"); // Notice the double backslash, since backslashes // need to be escaped } 

Here is a prototype from MSDN :

int _mkdir (const char * dirname);

+7
source

My cross-platform solution (recursive):

 #include <sstream> #include <sys/stat.h> // for windows mkdir #ifdef _WIN32 #include <direct.h> #endif namespace utils { /** * Checks if a folder exists * @param foldername path to the folder to check. * @return true if the folder exists, false otherwise. */ bool folder_exists(std::string foldername) { struct stat st; stat(foldername.c_str(), &st); return st.st_mode & S_IFDIR; } /** * Portable wrapper for mkdir. Internally used by mkdir() * @param[in] path the full path of the directory to create. * @return zero on success, otherwise -1. */ int _mkdir(const char *path) { #ifdef _WIN32 return ::_mkdir(path); #else #if _POSIX_C_SOURCE return ::mkdir(path); #else return ::mkdir(path, 0755); // not sure if this works on mac #endif #endif } /** * Recursive, portable wrapper for mkdir. * @param[in] path the full path of the directory to create. * @return zero on success, otherwise -1. */ int mkdir(const char *path) { std::string current_level = ""; std::string level; std::stringstream ss(path); // split path using slash as a separator while (std::getline(ss, level, '/')) { current_level += level; // append folder to the current level // create current level if (!folder_exists(current_level) && _mkdir(current_level.c_str()) != 0) return -1; current_level += "/"; // don't forget to append a slash } return 0; } } 
+7
source

There is currently _mkdir() .

+5
source

All Articles