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

C/C++判断一个文件是否存在
1.
判断路径文件夹是否存在,不存在创建 bool  isExistFile( const   char   * pszFileName) {
    FILE 
*fp = fopen(pszFileName, "rb");
    
if(fp == NULL)
        
return false;
    fclose(fp);
    
return true;
}

判断路径文件夹是否存在,不存在创建 bool  isExistFile( const   char   * pszFileName) {
        fstream file;
        file.open(pszFileName,ios::
in);
        
if(!file)
            
return false;

        
return true;
    }

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

函数名: access

//  crt_access.c
#include   < io.h >
#include  
< stdio.h >
#include  
< stdlib.h >

int  main(  void  )
判断路径文件夹是否存在,不存在创建
{
判断路径文件夹是否存在,不存在创建   

   
if(_access( "crt_ACCESS.C"0 )) != -1 )
判断路径文件夹是否存在,不存在创建   
{
      printf( 
"File crt_ACCESS.C exists\n" );
判断路径文件夹是否存在,不存在创建      

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

      
if(_access( "crt_ACCESS.C"2 )) == -1 )
         printf( 
"File crt_ACCESS.C does not have write permission\n" );
   }

}

3.用FindFirstFile


#include  < windows.h >
#include 
< string >  
#include 
< vector >
using   namespace  std; 

//  核查目录,若目录不存在,创建目录
bool  FindOrCreateDirectory(  const   char *  pszPath )
判断路径文件夹是否存在,不存在创建
{
    WIN32_FIND_DATA fd;
    HANDLE hFind 
= ::FindFirstFile( pszPath, &fd );
    
whilehFind != INVALID_HANDLE_VALUE )
判断路径文件夹是否存在,不存在创建    
{
        
if fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            
return true;
    }


    
if !::CreateDirectory( pszPath, NULL )
判断路径文件夹是否存在,不存在创建    
{
        
char szDir[MAX_PATH];
        sprintf_s( szDir, 
sizeof(szDir), "创建目录[%s]失败,请检查权限"pszPath );
        ::MessageBox( NULL, szDir, 
"创建目录失败"MB_OK|MB_ICONERROR );
        
return false;
    }


    
return true;
}


//  遍历目录
bool  CheckDirectory(  char *  pszPath )
判断路径文件夹是否存在,不存在创建
{
    vector
< std::string > vtPath;

    
const char* sep = "\\/";
    
char* next_token;
    
char* token =  strtok_s( pszPath, sep, &next_token);
    
whiletoken != NULL )
判断路径文件夹是否存在,不存在创建    
{
        vtPath.push_back( token );
        token 
= strtok_s(NULL, sep, &next_token);
    }


    
if vtPath.size() > 0 )
判断路径文件夹是否存在,不存在创建    
{
        
if vtPath[0== "." )
            vtPath.erase( vtPath.begin() );
    }


    
// 核查所有路径是否存在
    std::string strCurPath;
    
forsize_t = 0 < (int)vtPath.size(); ++)
判断路径文件夹是否存在,不存在创建    
{
        strCurPath 
+= vtPath[i];
        strCurPath 
+= '\\';

        
if !FindOrCreateDirectory( strCurPath.c_str() )
判断路径文件夹是否存在,不存在创建        
{
            
return false;
        }

    }


    
return true;
}



int  main() 
判断路径文件夹是否存在,不存在创建

    
char szPath[MAX_PATH] = "./main\\test\\hello/jump\\test\\";
    CheckDirectory( szPath );
    

    system(
"pause");
    
return 0
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值