C++ 一次创建多级目录
【摘要】 原文:http://www.cnblogs.com/tangxin-blog/p/6086425.html
c++中,<io.h>中的_access可以判断文件是否存在,<direct.h>中的_mkdir可以创建文件。 建单级目录:#include <io.h>#include <direct.h>#incl...
原文:http://www.cnblogs.com/tangxin-blog/p/6086425.html
-
c++中,<io.h>中的_access可以判断文件是否存在,<direct.h>中的_mkdir可以创建文件。
-
-
建单级目录:
-
#include <io.h>
-
#include <direct.h>
-
#include <string>
-
int main()
-
{
-
std::string prefix = "G:/test/";
-
if (_access(prefix.c_str(), 0) == -1) //如果文件夹不存在
-
_mkdir(prefix.c_str()); //则创建
-
}
-
建多级目录:
-
最后一个如果是文件夹的话,需要加上 '\\' 或者 '/'
-
#include <io.h>
-
#include <direct.h>
-
#include <string>
-
int createDirectory(std::string path)
-
{
-
int len = path.length();
-
char tmpDirPath[256] = { 0 };
-
for (int i = 0; i < len; i++)
-
{
-
tmpDirPath[i] = path[i];
-
if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
-
{
-
if (_access(tmpDirPath, 0) == -1)
-
{
-
int ret = _mkdir(tmpDirPath);
-
if (ret == -1) return ret;
-
}
-
}
-
}
-
return 0;
-
}
这是另一个版本,跨平台的:
-
#ifdef WIN32
-
#include <io.h>
-
#include <direct.h>
-
#else
-
#include <unistd.h>
-
#include <sys/stat.h>
-
#endif
-
#include <stdint.h>
-
#include <string>
-
#define MAX_PATH_LEN 256
-
-
#ifdef WIN32
-
#define ACCESS(fileName,accessMode) _access(fileName,accessMode)
-
#define MKDIR(path) _mkdir(path)
-
#else
-
#define ACCESS(fileName,accessMode) access(fileName,accessMode)
-
#define MKDIR(path) mkdir(path,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
-
#endif
-
-
// 从左到右依次判断文件夹是否存在,不存在就创建
-
// example: /home/root/mkdir/1/2/3/4/
-
// 注意:最后一个如果是文件夹的话,需要加上 '\' 或者 '/'
-
int32_t createDirectory(const std::string &directoryPath)
-
{
-
uint32_t dirPathLen = directoryPath.length();
-
if (dirPathLen > MAX_PATH_LEN)
-
{
-
return -1;
-
}
-
char tmpDirPath[MAX_PATH_LEN] = { 0 };
-
for (uint32_t i = 0; i < dirPathLen; ++i)
-
{
-
tmpDirPath[i] = directoryPath[i];
-
if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
-
{
-
if (ACCESS(tmpDirPath, 0) != 0)
-
{
-
int32_t ret = MKDIR(tmpDirPath);
-
if (ret != 0)
-
{
-
return ret;
-
}
-
}
-
}
-
}
-
return 0;
-
}
-
-
int32_t main(int32_t argc, char *argv[])
-
{
-
if (argc == 2)
-
{
-
return createDirectory(argv[1]);
-
}
-
return 0;
-
}
文章来源: blog.csdn.net,作者:网奇,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/jacke121/article/details/78467086
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)