unix环境高级编程--不带缓冲的IO操作

约定不等于承诺〃 2022-06-13 14:20 235阅读 0赞

最近在学习linux环境下的编程,《UNIX环境高级编程》自不用说,是经典中的经典了。下面贴出我的测试代码,测试环境ubuntu11.10, gcc编译通过

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. char buf1[] = "abcdefghij";
  6. char buf2[] = "ABCDEFGHIJ";
  7. void stdio_test();
  8. int main(int argc, char *argv[])
  9. {
  10. // iotest();
  11. stdio_test();
  12. return 0;
  13. }
  14. #define BUFFSIZE 4096
  15. void stdio_test()
  16. {
  17. int n;
  18. char buf[BUFFSIZE];
  19. while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
  20. {
  21. if (write(STDOUT_FILENO, buf, n) != n)
  22. {
  23. printf("write err\n");
  24. }
  25. }
  26. if (n < 0)
  27. {
  28. printf("read err");
  29. }
  30. exit(0);
  31. }
  32. void iotest()
  33. {
  34. int fd = 0;
  35. int iRet = 0;
  36. char buf_to_read[30] = {0};
  37. fd = open("example", O_RDWR | O_CREAT, 00644);
  38. if (fd == -1)
  39. {
  40. printf("open err\n");
  41. return;
  42. }
  43. if (write(fd, buf1, 10) != 10)
  44. {
  45. printf("write buf1 err\n");
  46. return;
  47. }
  48. //这个地方lseek一定要有,否则下一步read会失败,目的是将文件偏移指针移到文件首,因为write会更改文件偏移指针
  49. if (lseek(fd, 0, SEEK_SET) == -1)
  50. {
  51. printf("lseek err\n");
  52. return;
  53. }
  54. if (read(fd, buf_to_read, 30) == -1)
  55. {
  56. printf("read err\n");
  57. return;
  58. }
  59. printf("read: %s\n", buf_to_read);
  60. exit(0);
  61. }

编译命令:gcc ioexample.c

编译成功后运行:./a.out

结果:自己试去吧。

水平有限,如果有朋友发现错误,欢迎留言交流。

转载请保留本文链接,如果觉得我的文章能帮到您,请顶一下。,谢谢。

发表评论

表情:
评论列表 (有 0 条评论,235人围观)

还没有评论,来说两句吧...

相关阅读