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

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

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 = 0i <leni++)

{

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

}

用IF NOT EXIST "G:\%DATE:~0,10%tst" MD "G:\%DATE:~0,10%tst"

例如:

IF EXIST C:\DATE (

 del filename.

) ELSE (

 echo filename. missing.

)

扩展资料:

注意事项

@echo off

@title 批处理判断文件夹是否存在

if exist folder1 (

echo "已经存在文件夹"

) else (

md folder1

)

if not exist folder2 md folder2

pause

命令中首先判断当前目录中是否存在folder1,如果存在,打印“已经存在文件夹”如果不存在就用md命令建立文件夹。

参考代码如下:

#include <stdio.h>

#include <direct.h>

#include <stdlib.h>

#include <memory>

//检查文件夹是否存在,不存在则创建之

//文件夹存在返回 0

//文件夹创建失败返回-1

//文件夹创建失败返回1

int CheckDir(char* Dir)

{

FILE *fp = NULL

char TempDir[200]

memset(TempDir,'\0',sizeof(TempDir))

sprintf(TempDir,Dir)

strcat(TempDir,"\\")

strcat(TempDir,".temp.fortest")

fp = fopen(TempDir,"w")

if (!fp)

{

if(_mkdir(Dir)==0)

{

return 1//文件夹创建成功

}

else

{

return -1//can not make a dir

}

}

else

{

fclose(fp)

}

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12052918.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存