C++ 一次创建多级目录

举报
风吹稻花香 发表于 2021/06/05 01:43:00 2021/06/05
【摘要】 原文: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

 


  
  1. c++中,<io.h>中的_access可以判断文件是否存在,<direct.h>中的_mkdir可以创建文件。
  2. 建单级目录:
  3. #include <io.h>
  4. #include <direct.h>
  5. #include <string>
  6. int main()
  7. {
  8. std::string prefix = "G:/test/";
  9. if (_access(prefix.c_str(), 0) == -1) //如果文件夹不存在
  10. _mkdir(prefix.c_str()); //则创建
  11. }
  12. 建多级目录:
  13. 最后一个如果是文件夹的话,需要加上 '\\' 或者 '/'
  14. #include <io.h>
  15. #include <direct.h>
  16. #include <string>
  17. int createDirectory(std::string path)
  18. {
  19. int len = path.length();
  20. char tmpDirPath[256] = { 0 };
  21. for (int i = 0; i < len; i++)
  22. {
  23. tmpDirPath[i] = path[i];
  24. if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
  25. {
  26. if (_access(tmpDirPath, 0) == -1)
  27. {
  28. int ret = _mkdir(tmpDirPath);
  29. if (ret == -1) return ret;
  30. }
  31. }
  32. }
  33. return 0;
  34. }

是另一个版本,跨平台的:

 

   
  1. #ifdef WIN32
  2. #include <io.h>
  3. #include <direct.h>
  4. #else
  5. #include <unistd.h>
  6. #include <sys/stat.h>
  7. #endif
  8. #include <stdint.h>
  9. #include <string>
  10. #define MAX_PATH_LEN 256
  11. #ifdef WIN32
  12. #define ACCESS(fileName,accessMode) _access(fileName,accessMode)
  13. #define MKDIR(path) _mkdir(path)
  14. #else
  15. #define ACCESS(fileName,accessMode) access(fileName,accessMode)
  16. #define MKDIR(path) mkdir(path,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
  17. #endif
  18. // 从左到右依次判断文件夹是否存在,不存在就创建
  19. // example: /home/root/mkdir/1/2/3/4/
  20. // 注意:最后一个如果是文件夹的话,需要加上 '\' 或者 '/'
  21. int32_t createDirectory(const std::string &directoryPath)
  22. {
  23. uint32_t dirPathLen = directoryPath.length();
  24. if (dirPathLen > MAX_PATH_LEN)
  25. {
  26. return -1;
  27. }
  28. char tmpDirPath[MAX_PATH_LEN] = { 0 };
  29. for (uint32_t i = 0; i < dirPathLen; ++i)
  30. {
  31. tmpDirPath[i] = directoryPath[i];
  32. if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
  33. {
  34. if (ACCESS(tmpDirPath, 0) != 0)
  35. {
  36. int32_t ret = MKDIR(tmpDirPath);
  37. if (ret != 0)
  38. {
  39. return ret;
  40. }
  41. }
  42. }
  43. }
  44. return 0;
  45. }
  46. int32_t main(int32_t argc, char *argv[])
  47. {
  48. if (argc == 2)
  49. {
  50. return createDirectory(argv[1]);
  51. }
  52. return 0;
  53. }

 

 

 

文章来源: blog.csdn.net,作者:网奇,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jacke121/article/details/78467086

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。