忘了在那看到的了,写到这,记录一下
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;
}