. unix环境高级编程--不带缓冲的IO操作
linux环境下的编程。测试代码,测试环境ubuntu11.10, gcc编译通过
[cpp] view plaincopy
01.<span style="font-family: Microsoft YaHei; font-size: 18px;">#include <stdio.h>
02.#include <stdlib.h>
03.#include <unistd.h>
04.#include <fcntl.h>
05.
06.char buf1[] = "abcdefghij";
07.char buf2[] = "ABCDEFGHIJ";
08.
09.
10.void stdio_test();
11.
12.int main(int argc, char *argv[])
13.{
14.// iotest();
15. stdio_test();
16. return 0;
17.
18.}
19.
20.#define BUFFSIZE 4096
21.void stdio_test()
22.{
23. int n;
24. char buf[BUFFSIZE];
25.
26. while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
27. {
28. if (write(STDOUT_FILENO, buf, n) != n)
29. {
30. printf("write err\n");
31. }
32. }
33.
34. if (n < 0)
35. {
36. printf("read err");
37. }
38. exit(0);
39.}
40.
41.void iotest()
42.{
43. int fd = 0;
44. int iRet = 0;
45. char buf_to_read[30] = {0};
46.
47. fd = open("example", O_RDWR O_CREAT, 00644);
48. if (fd == -1)
49. {
50. printf("open err\n");
51. return;
52. }
53.
54. if (write(fd, buf1, 10) != 10)
55. {
56. printf("write buf1 err\n");
57. return;
58. }
59.
60.//这个地方lseek一定要有,否则下一步read会失败,目的是将文件偏移指针移到文件首,因为write会更改文件偏移指针
61. if (lseek(fd, 0, SEEK_SET) == -1)
62. {
63. printf("lseek err\n");
64. return;
65. }
66.
67.
68. if (read(fd, buf_to_read, 30) == -1)
69. {
70. printf("read err\n");
71. return;
72. }
73.
74. printf("read: %s\n", buf_to_read);
75. exit(0);
76.}</span>
编译命令:gcc ioexample.c
编译成功后运行:./a.out
结果:自己试去吧。