屏蔽字O_ACCMODE 整数常量

来源:互联网 发布:php print 编辑:程序博客网 时间:2024/05/18 01:38

Macro: int O_ACCMODE

This macro stands for a mask that can be bitwise-ANDed with the file status flag value to produce a value representing the file access mode. The mode will be O_RDONLYO_WRONLY, or O_RDWR. (In the GNU system it could also be zero, and it never includes the O_EXEC bit.)

这个宏作为一个掩码与文件状态标识值做AND位运算,产生一个表示文件访问模式的值。这模式将是O_RDONLY, O_WRONLY, 或 O_RDWR(在GNU系统中,也可能是零,并且从不包括 O_EXEC 位)


 O_ACCMODE<0003>:读写文件操作时,用于取出flag的低2位

O_RDONLY<00>:只读打开
O_WRONLY<01>:只写打开
O_RDWR<02>:读写打开

 

#include "apue.h"
#include <fcntl.h>

int
main(int argc, char *argv[])
{
 int  val;

 if (argc != 2)
  err_quit("usage: a.out <descriptor#>");

 if ((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0)
  err_sys("fcntl error for fd %d", atoi(argv[1]));

 switch (val & O_ACCMODE) {
 case O_RDONLY:
  printf("read only");
  break;

 case O_WRONLY:
  printf("write only");
  break;

 case O_RDWR:
  printf("read write");
  break;

 default:
  err_dump("unknown access mode");
 }

 if (val & O_APPEND)
  printf(", append");
 if (val & O_NONBLOCK)
  printf(", nonblocking");
#if defined(O_SYNC)
 if (val & O_SYNC)
  printf(", synchronous writes");
#endif
#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)
 if (val & O_FSYNC)
  printf(", synchronous writes");
#endif
 putchar('\n');
 exit(0);
}

0 0