歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 《APUE》:打印指定的描述符的文件標志

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

日期:2017/3/1 10:12:04   编辑:Linux編程

《Unix環境高級編程》這本書附帶了許多短小精美的小程序,我在閱讀此書的時候,將書上的代碼按照自己的理解重寫了一遍(大部分是抄書上的),加深一下自己的理解(純看書太困了,呵呵)。此例子在Ubuntu 10.04上測試通過。

相關鏈接

  • 《UNIX環境高級編程》(第二版)apue.h的錯誤 http://www.linuxidc.com/Linux/2011-04/34662.htm
  • Unix環境高級編程 源代碼地址 http://www.linuxidc.com/Linux/2011-04/34826.htm
  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. int main(int argc, char **argv)
  8. {
  9. int val;
  10. if( argc != 2 )
  11. {
  12. fprintf(stderr, "Usage: a.out <descriptor#>");
  13. exit(1);
  14. }
  15. //改變已打開的文件的性質
  16. val = fcntl( atoi(argv[1]), F_GETFL, 0);
  17. if( val < 0 )
  18. {
  19. fprintf(stderr, "fcntl error for fd %d", atoi(argv[1]));
  20. exit(1);
  21. }
  22. //打印所選擇文件的標志說明
  23. switch(val & O_ACCMODE)
  24. {
  25. case O_RDONLY:
  26. printf("Read Only");
  27. break;
  28. case O_WRONLY:
  29. printf("write only");
  30. break;
  31. case O_RDWR:
  32. printf("read write");
  33. break;
  34. default:
  35. fprintf(stderr, "unknow access mode");
  36. exit(1);
  37. }
  38. if( val & O_APPEND )
  39. printf(", append");
  40. if( val & O_NONBLOCK )
  41. printf(", nonblocking");
  42. #if defined(O_SYNC)
  43. if( val & O_SYNC )
  44. printf(", synchronous writes");
  45. #endif
  46. #if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)
  47. if( val & O_FSYNC )
  48. printf(", synchronous writes");
  49. #endif
  50. putchar('\n');
  51. return 0;
  52. }
Copyright © Linux教程網 All Rights Reserved