关于C++中如何判断文件,目录存在的若干方法

在我们平时的编程时,经常需要判断文件或者目录是否存在,相对来说判断文件的存在性比较简单,目录则比较复杂。

下面就详细的介绍几种方法。

 

首先关于判断文件的存在性:

一、ifstream

在C++中,可以利用ifstream文件输入流,当我们直接使用ifstream来创建文件输入流的时候,如果文件不存在则流创建失败。

ifstream fin( " hello.txt " );
if  ( ! fin)
{
   std::cout 
<<   " can not open this file "   <<  endl;

这是c++中最常用的方式。

 

二、File

C中也是同样道理,我们可是File的相关操作。

File *  fh  =  fopen( " hello " , " r " );
if (fh  ==  NULL)
{
   printf(
" %s " , " can not open the file " );
}

 

三、_access

当然C中还有一种方式是直接调用c的函数库。

就是函数 int _access(const char* path,int mode);

这个函数的功能十分强大。

可以看看msdn的详细介绍

复制代码
#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 "  );
    }
}
复制代码

 

这三种方式算是判断文件存在比较简单快捷的方法了。

 

 

现在来说说判断目录存在的一些方法。

一、FindFirstFile

在C++中可以调用系统的一些函数,但这种方法稍微显得复杂一些。

复制代码
WIN32_FIND_DATA wfd;
bool  rValue  =   false ;
HANDLE hFind 
=  FindFirstFile(strPath.c_str(),  & wfd);
if  ((hFind  !=  INVALID_HANDLE_VALUE)  &&  (wfd.dwFileAttributes  &  FILE_ATTRIBUTE_DIRECTORY))
{
   std::cout 
<<   " this file exists "   <<  endl;
}
FindClose(hFind);
复制代码

 

二、_stat()

现在介绍一个轻量级的方法

在windows中可以使用_stat() 函数。

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

这个函数使用起来非常方便,如下:

struct  _stat fileStat;
if  ((_stat(dir.c_str(),  & fileStat)  ==   0 &&  (fileStat.st_mode  &  _S_IFDIR))
{
    isExist 
=   true ;
}

_S_IFDIR 是一个标志位,如果是目录的话,该位就会被系统设置。

在linux底下也有相对应的函数stat();

使用方法基本相同:

struct  stat fileStat;
if  ((stat(dir.c_str(),  & fileStat)  ==   0 &&  S_ISDIR(fileStat.st_mode))
{
    isExist 
=   true ;
}

唯一不同的地方我使用了一个macro, S_ISDIR来判断文件是否存在,原理实际都一样的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值