我需要在VS 2008中使用mkdir c ++函数,该函数接受两个参数,并且在VS 2005中已弃用。
但是我们的代码中使用了这个函数,我需要编写一个独立的产品(只包含mkdir函数)来调试。
我需要导入哪些头文件?我使用了direct.h,但是编译器抱怨该参数不带2个参数(原因是这个函数在VS 2005中已被弃用)。
mkdir("C:\hello",0);
答案 0 :(得分:12)
如果要编写跨平台代码,可以使用boost::filesystem
例程
#include <boost/filesystem.hpp>
boost::filesystem::create_directory("dirname");
这确实增加了一个库依赖项,但是你也可能会使用其他文件系统例程,boost::filesystem
有一些很棒的接口。
如果您只需要创建一个新目录,并且只打算使用VS 2008,则可以使用其他人注意到的_mkdir()
。
答案 1 :(得分:7)
它已被弃用,但符合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);
答案 2 :(得分:7)
我的跨平台解决方案(递归):
#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;
}
}
答案 3 :(得分:5)
现在有_mkdir()
功能。