1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 判断路径文件夹是否存在 不存在创建

判断路径文件夹是否存在 不存在创建

时间:2020-09-02 16:39:44

相关推荐

判断路径文件夹是否存在 不存在创建

C/C++判断一个文件是否存在

1.

boolisExistFile( constchar* pszFileName) {

FILE*fp=fopen(pszFileName,"rb");

if(fp==NULL)

returnfalse;

fclose(fp);

returntrue;

} 或

boolisExistFile( constchar* pszFileName) {

fstreamfile;

file.open(pszFileName,ios::in);

if(!file)

returnfalse;

returntrue;

}

2. 利用 c 语言的库的办法:

函数名: access

//crt_access.c

#include< io.h >

#include< stdio.h >

#include< stdlib.h >

intmain(void)

{

if((_access("crt_ACCESS.C",0))!=-1)

{

printf("Filecrt_ACCESS.Cexists\n");

if((_access("crt_ACCESS.C",2))==-1)

printf("Filecrt_ACCESS.Cdoesnothavewritepermission\n");

}

}

3.用FindFirstFile

#include< windows.h >

#include< string >

#include< vector >

usingnamespacestd;

//核查目录,若目录不存在,创建目录

boolFindOrCreateDirectory(constchar *pszPath)

{

WIN32_FIND_DATAfd;

HANDLEhFind=::FindFirstFile(pszPath,&fd);

while(hFind!=INVALID_HANDLE_VALUE)

{

if(fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)

returntrue;

}

if(!::CreateDirectory(pszPath,NULL))

{

charszDir[MAX_PATH];

sprintf_s(szDir,sizeof(szDir),"创建目录[%s]失败,请检查权限",pszPath);

::MessageBox(NULL,szDir,"创建目录失败",MB_OK|MB_ICONERROR);

returnfalse;

}

returntrue;

}

//遍历目录

boolCheckDirectory(char *pszPath)

{

vector<std::string>vtPath;

constchar*sep="\\/";

char*next_token;

char*token=strtok_s(pszPath,sep,&next_token);

while(token!=NULL)

{

vtPath.push_back(token);

token=strtok_s(NULL,sep,&next_token);

}

if(vtPath.size()>0)

{

if(vtPath[0]==".")

vtPath.erase(vtPath.begin());

}

//核查所有路径是否存在

std::stringstrCurPath;

for(size_ti=0;i<(int)vtPath.size();++i)

{

strCurPath+=vtPath[i];

strCurPath+='\\';

if(!FindOrCreateDirectory(strCurPath.c_str()))

{

returnfalse;

}

}

returntrue;

}

intmain()

{

charszPath[MAX_PATH]="./main\\test\\hello/jump\\test\\";

CheckDirectory(szPath);

system("pause");

return0;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。