![判断路径文件夹是否存在 不存在创建](https://1500zi.500zi.com/uploadfile/img/15/137/17772a2b7503c5eaa60acc3ee88e5738.jpg)
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;
}