《APUE》:打印指定的描述符的文件标志


《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu 10.04上测试通过。

相关链接

  • 《UNIX环境高级编程》(第二版)apue.h的错误
  • Unix环境高级编程 源代码地址
  1. //《Unix环境高级编程》程序3-4:打印指定的描述符的文件标志   
  2. #include <stdio.h>     
  3. #include <string.h>     
  4. #include <fcntl.h>     
  5. #include <unistd.h>     
  6. #include <stdlib.h>   
  7.     
  8. int main(int argc, char **argv)    
  9. {    
  10.     int val;    
  11.     if( argc != 2 )    
  12.     {    
  13.         fprintf(stderr, "Usage: a.out <descriptor#>");    
  14.         exit(1);    
  15.     }    
  16.     //改变已打开的文件的性质     
  17.     val = fcntl( atoi(argv[1]), F_GETFL, 0);    
  18.     if( val < 0 )    
  19.     {    
  20.         fprintf(stderr, "fcntl error for fd %d", atoi(argv[1]));    
  21.         exit(1);    
  22.     }    
  23.     
  24.     //打印所选择文件的标志说明     
  25.     switch(val & O_ACCMODE)    
  26.     {    
  27.     case O_RDONLY:    
  28.         printf("Read Only");    
  29.         break;    
  30.     case O_WRONLY:    
  31.         printf("write only");    
  32.         break;    
  33.     case O_RDWR:    
  34.         printf("read write");    
  35.         break;    
  36.     default:    
  37.         fprintf(stderr, "unknow access mode");    
  38.         exit(1);    
  39.     }    
  40.     
  41.     if( val & O_APPEND )    
  42.         printf(", append");    
  43.     if( val & O_NONBLOCK )    
  44.         printf(", nonblocking");    
  45.     
  46. #if defined(O_SYNC)     
  47.     if( val & O_SYNC )    
  48.         printf(", synchronous writes");    
  49. #endif     
  50.     
  51. #if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)     
  52.     if( val & O_FSYNC )    
  53.         printf(", synchronous writes");    
  54. #endif     
  55.     putchar('\n');    
  56.     return 0;    
  57. }    

相关内容