c++ 判断文件夹是否存在,不存在则创建

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;

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容