C语言,如何检查文件是否存在和权限的信息

按功能access,头文件io.h(linux通过使用unistd.h   
int   access(const   char   *filename,   int   amode);

amode參数为0时表示检查文件的存在性,假设文件存在。返回0。不存在,返回-1。



这个函数还能够检查其他文件属性:

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

在UNIX和VC下实验成功。

优点是 fopen(..,"r")不好,当无读权限时一不行了。


而这个就算这个文件没有读权限。也能够推断这个文件存在于否

存在返回0。不存在返回-1

#include <stdio.h>
int main()
{
	printf ("%d",access("test.db",0));
}

測试程序

#define __WINDOWS__		// windows系统使用
//#define __LINUX__		// linux系统下使用

#ifdef __WINDOWS__
#include <io.h>
#endif

#ifdef __LINUX__
#include <unistd.h>
#endif


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


#define FILE_NAME  "test.db"

int main( void )
{
	/* Check for existence */
	if( (access(FILE_NAME, 0 )) != -1 )
	{
		printf( "File [ %s ] exists
", FILE_NAME);
		/* Check for write permission */
		if( (_access(FILE_NAME, 2 )) != -1 )
		{
			printf( "File [ %s ] has write permission
", FILE_NAME);
		}
		else
		{
			printf( "File [ %s ] has not write permission
", FILE_NAME);
		}
	}
	else
	{
		printf( "File [ %s ] don't exists
", FILE_NAME);
	}
}


版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/bhlsheji/p/4638341.html