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;  
}

 

發佈了45 篇原創文章 · 獲贊 30 · 訪問量 63萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章