C

C函数access的用法

Posted by AndyCao on December 4, 2019

函数定义

int access(const char * pathname, int mode)

作用:用以检查是否可以对指定的文件执行某种操作

参数

  • pathname: 需要检测的文件路径名
  • mode: 需要测试的操作模式

mode说明:

#define F_OK            0       /* test for existence of file */
#define X_OK            (1<<0)  /* test for execute or search permission */
#define W_OK            (1<<1)  /* test for write permission */
#define R_OK            (1<<2)  /* test for read permission */
#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)
/*
 * Extended access functions.
 * Note that we depend on these matching the definitions in sys/kauth.h,
 * but with the bits shifted left by 8.
 */
#define _READ_OK        (1<<9)  /* read file data / read directory */
#define _WRITE_OK       (1<<10) /* write file data / add file to directory */
#define _EXECUTE_OK     (1<<11) /* execute file / search in directory*/
#define _DELETE_OK      (1<<12) /* delete file / delete directory */
#define _APPEND_OK      (1<<13) /* append to file / add subdirectory to directory */
#define _RMFILE_OK      (1<<14) /* - / remove file from directory */
#define _RATTR_OK       (1<<15) /* read basic attributes */
#define _WATTR_OK       (1<<16) /* write basic attributes */
#define _REXT_OK        (1<<17) /* read extended attributes */
#define _WEXT_OK        (1<<18) /* write extended attributes */
#define _RPERM_OK       (1<<19) /* read permissions */
#define _WPERM_OK       (1<<20) /* write permissions */
#define _CHOWN_OK       (1<<21) /* change ownership */

#define _ACCESS_EXTENDED_MASK (_READ_OK | _WRITE_OK | _EXECUTE_OK | \
	                        _DELETE_OK | _APPEND_OK | \
	                        _RMFILE_OK | _REXT_OK | \
	                        _WEXT_OK | _RATTR_OK | _WATTR_OK | _RPERM_OK | \
	                        _WPERM_OK | _CHOWN_OK)
#endif

返回值

成功执行时,返回0。失败返回-1

函数实例

int test()
{
  if(access("test.txt", R_OK)==0)  printf("READ OK\n");
  if(access("test.txt", W_OK)==0)  printf("WRITE OK\n");
  if(access("test.txt", X_OK)==0)  printf("EXEC OK\n");
  if(access("test.txt", F_OK)==0)  printf("File exist\n");
}