Bru*_*uce 11 c++ visual-studio-2008
我需要在VS 2008中使用mkdir c ++函数,该函数有两个参数,并且在VS 2005中已弃用.
但是我们的代码中使用了这个函数,我需要编写一个独立的产品(只包含mkdir函数)来调试.
我需要导入哪些头文件?我使用了direct.h,但是编译器抱怨该参数不带2个参数(原因是这个函数在VS 2005中已被弃用).
mkdir("C:\hello",0);
Run Code Online (Sandbox Code Playgroud)
小智 15
如果要编写跨平台代码,可以使用boost::filesystem例程
#include <boost/filesystem.hpp>
boost::filesystem::create_directory("dirname");
Run Code Online (Sandbox Code Playgroud)
这确实增加了一个库依赖项,但是你也可能会使用其他文件系统例程,并且boost::filesystem有一些很好的接口.
如果您只需要创建一个新目录,并且您只打算使用VS 2008,则可以_mkdir()像其他人一样注意使用.
Mic*_*eyn 10
它已被弃用,但ISO C++符合_mkdir()替换它,因此请使用该版本.你只需要调用它就是目录名,它唯一的参数:
#include <direct.h>
void foo()
{
_mkdir("C:\\hello"); // Notice the double backslash, since backslashes
// need to be escaped
}
Run Code Online (Sandbox Code Playgroud)
这是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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23310 次 |
| 最近记录: |