c++ 判断文件、文件夹(路径)是否存在

1. 判断文件是否存在

例如:#include <fstream>  // fstream

     std::fstream _file;
     _file.open(g_sFaceFeaturePath.c_str(),ios::in);
     if(!_file)
     {   
         cout<< "Cannot find file:"<<endl;
         exit(-1);          
     }

   remove("./1.txt");   // 删除文件, #include "stdlib.h"  //atoi


2.判断路径或文件夹是否存在

例如:#include <dirent.h>   //DIR *dir

string g_sSamplePath = "./train/";

  DIR *dir;   
   if ((dir=opendir(g_sSamplePath.c_str())) == NULL)   
   {   
        system("mkdir -p ./train/");      //system( s.c_str() );
   }  

 system("rm -rf ./Result");    //删除文件夹
 system("mkdir -p ./Result");  //创建文件夹


例如:

vector<string> vsFileName;

GetDirAllFile("./train", "", vsFileName);   //获得文件夹的名字

GetDirAllFile("./train", ".bmp", vsFileName);   //获得文件的名字



void CFaceProcess::GetDirAllFile(string sPath, string sTemplate, vector<string> &_vsFileName)
{
    DIR *dir;   
    struct dirent *ptr;    
    _vsFileName.clear();
    string s = " ";
    string ss = " ";
    int n = sTemplate.length();

    if ((dir=opendir(sPath.c_str())) == NULL)   
    {   
        perror("Open dir error...");   
        exit(1);          
    }   
    // readdir() return next enter point of directory dir  
    while ((ptr=readdir(dir)) != NULL)   
    {    
        s = ptr->d_name; //cout<<s<<endl;
        
        if (n > 0)
        {
           if (n < s.length())
           {
              ss = s.substr(s.length()-n); //从索引11往后的子串
              if (!ss.compare(sTemplate)) //==
                _vsFileName.push_back(s);
           }
        }
        else
        {  
           if (s.compare(".") && s.compare("..")) //compare() 返回true,表示等于
           {
              _vsFileName.push_back(s);
           }
        }
    }
  
    closedir(dir);  
}

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值