C++ 判断文件文件夹是否存在

判断文件是否存在

  1. ifstream

用ifstream创建文件的输入流,如果文件不存在,则输入流创建失败。

ifstream fin("hello.txt");
  if(!fin){
      //TODO
  }
  1. File

用File来判断文件是否存在

File *fh = fopen("hello.txt","r");
  if(fh == NULL){
      //TODO    
  }
  1. _acess()

int _access( const char *path, int mode );
可以用来查看文件是否存在,是否可写读;仅存在mode为00,可写02,可读04 可读写06;仅在返回0时表示存在或者具有指定特性值;对目录使用时仅表示目录是否存在

#include  <io.h>  
  #include  <stdio.h>  
  #include  <stdlib.h>  
    
  int main( void )  
  {  
      // Check for existence.  
      if( (_access( "crt_ACCESS.C", 0 )) != -1 )  
      {  
          printf_s( "File crt_ACCESS.C exists.\n" ); 

          // Check for write permission.  
          // Assume file is read-only.  
          if( (_access( "crt_ACCESS.C", 2 )) == -1 )  
          printf_s( "File crt_ACCESS.C does not have write permission.\n" );  
      }  
  }

判断文件夹是否存在

  1. _stat() (linux中为stat())

int _stat(const char* path, struct _stat* buffer);

int _stat((dir.c_str(), &fileStat) == 0)&& (fileStat.st_mode & _S_IFDIR)){
      //TODO    
   }

其中_S_IFDIR是个标志位,为目录改为就会被系统设置

  1. GetFileAttributesA()

DWORD d = GetFileAttributesA(const char* filename); #include <windows.h> 为windows系统函数,判断文件目录是否存在

bool dirExists(const std::string& dirName_in)  
  {  
      DWORD ftyp = GetFileAttributesA(dirName_in.c_str());  
      if (ftyp == INVALID_FILE_ATTRIBUTES)  
           return false;  //something is wrong with your path!  

      if (ftyp & FILE_ATTRIBUTE_DIRECTORY)  
          return true;   // this is a directory!  

      return false;    // this is not a directory!  
  }

参考:

  1. 关于C++中如何判断文件,目录存在的若干方法
  2. C++ - 判断文件夹(folder)是否存在(exist)
  3. Linux C编程--目录文件操作
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值