C 判断文件是否存在

忘了在那看到的了,写到这,记录一下

 

1)access
2)fopen
3)stat       fstat?

>>>>>
应当使用函数access,头文件是io.h,原型:  

int   access(const   char   *filename,   int   amode);  

amode参数为0时表示检查文件的存在性,如果文件存在,返回0,不存在,返回-1。  

这个函数还可以检查其它文件属性:  

06     检查读写权限  
04     检查读权限  
02     检查写权限  
01     检查执行权限  
00     检查文件的存在性   

int access(const char *path, int amode);

If the requested access is permitted, access() succeeds and shall return 0; otherwise, -1 shall be returned and errno shall be set to indicate the error.

检测文件是否存在:access(filename, 0)
如果返回0,表示文件存在,否则不存在。

>>>>>
access和stat都是可以的。其实,stat是更底层的函数,一般OS把它实现为系统调用。那么,包括access和fopen这些函数都会调用 stat检查文件的权限和程序执行者的权限是否匹配,在LINUX、UNIX这些文件系统实现得比较好得OS中尤其如此。


>>>>>
int is_file_exist(const char * file_path)
{
struct stat stat_buf;

if(lstat(file_path, &stat_buf)<0)
return -1;

if(0 == S_ISREG(stat_buf.st_mode))
return -1;

return 0;       
}

>>>>>
Example  

/*   ACCESS.C:   This   example   uses   _access   to   check   the  
*   file   named   "ACCESS.C"   to   see   if   it   exists   and   if  
*   writing   is   allowed.  
*/  

#include      <io.h>  
#include      <stdio.h>  
#include      <stdlib.h>  

void   main(   void   )  
{  
/*   Check   for   existence   */  
if(   (_access(   "ACCESS.C",   0   ))   !=   -1   )  
{  
printf(   "File   ACCESS.C   exists\n"   );  
/*   Check   for   write   permission   */  
if(   (_access(   "ACCESS.C",   2   ))   !=   -1   )  
printf(   "File   ACCESS.C   has   write   permission\n"   );  
}  
}  


Output  

File   ACCESS.C   exists  
File   ACCESS.C   has   write   permission


>>>>>
#include

int main(int argc,char **argv)
{
int rt_fi;
int ii;
char flnm[1023];

for (ii=0;ii  strcpy(flnm,argv[1]);
rt_fi = access(flnm,F_OK);
if (rt_fi==0){ printf("file of %s is exist.\n",flnm);}
else {printf("file of %s is not exist!\n",flnm);}
return(0);
}


>>>>>
FILE   *fp;  
if(fp   =   fopen("c:\\a.txt","rb")   ==   NULL)  
{  
cout<<"The   file   is   not   exist!\n";  
return   0;  
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值