c++ 判斷文件夾是否存在,不存在則創建(可建多級目錄)

c++中,<io.h>中的_access可以判斷文件是否存在,<direct.h>中的_mkdir可以創建文件。

建單級目錄:

  1. #include <io.h>
  2. #include <direct.h>
  3. #include <string>
  4. int main()
  5. {
  6. std::string prefix = "G:/test/";
  7. if (_access(prefix.c_str(), 0) == -1) //如果文件夾不存在
  8. _mkdir(prefix.c_str()); //則創建
  9. }

 

建多級目錄:

最後一個如果是文件夾的話,需要加上 '\\' 或者 '/'

  1. #include <io.h>
  2. #include <direct.h>
  3. #include <string>
  4. int createDirectory(std::string path)
  5. {
  6. int len = path.length();
  7. char tmpDirPath[256] = { 0 };
  8. for (int i = 0; i < len; i++)
  9. {
  10. tmpDirPath[i] = path[i];
  11. if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
  12. {
  13. if (_access(tmpDirPath, 0) == -1)
  14. {
  15. int ret = _mkdir(tmpDirPath);
  16. if (ret == -1) return ret;
  17. }
  18. }
  19. }
  20. return 0;
  21. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章