mkdir c++ function

mkdir c++ function

本文关键字:function c++ mkdir      更新时间:2023-10-16

我需要在VS 2008中使用mkdir c ++函数,该函数接受两个参数,并且从VS 2005中已弃用。

但是,这个函数在我们的代码中使用,我需要编写一个独立的产品(只包含 mkdir 函数)来调试一些东西。

我需要导入哪些头文件?我使用了 direct.h,但是编译器抱怨该参数不接受 2 个参数(原因是该函数在 VS 2005 中已弃用)。

mkdir("C:hello",0);

如果要编写跨平台代码,可以使用boost::filesystem例程

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

这确实增加了库依赖性,但您可能还会使用其他文件系统例程,boost::filesystem有一些很棒的接口。

如果你只需要创建一个新目录,并且你只打算使用VS 2008,你可以使用_mkdir(),正如其他人所指出的那样。

它已被弃用,但符合 ISO C++ _mkdir()替换它,因此请使用该版本。您只需要调用目录名称,它的唯一参数:

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

以下是 MSDN 的原型:

int _mkdir( const char *dirname );

我的跨平台解决方案(递归):

#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;
    }
}

现在有_mkdir()功能。