unix环境高级编程--不带缓冲的IO操作
最近在学习linux环境下的编程,《UNIX环境高级编程》自不用说,是经典中的经典了。下面贴出我的测试代码,测试环境ubuntu11.10, gcc编译通过
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
char buf1[] = "abcdefghij";
char buf2[] = "ABCDEFGHIJ";
void stdio_test();
int main(int argc, char *argv[])
{
// iotest();
stdio_test();
return 0;
}
#define BUFFSIZE 4096
void stdio_test()
{
int n;
char buf[BUFFSIZE];
while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
{
if (write(STDOUT_FILENO, buf, n) != n)
{
printf("write err\n");
}
}
if (n < 0)
{
printf("read err");
}
exit(0);
}
void iotest()
{
int fd = 0;
int iRet = 0;
char buf_to_read[30] = {0};
fd = open("example", O_RDWR | O_CREAT, 00644);
if (fd == -1)
{
printf("open err\n");
return;
}
if (write(fd, buf1, 10) != 10)
{
printf("write buf1 err\n");
return;
}
//这个地方lseek一定要有,否则下一步read会失败,目的是将文件偏移指针移到文件首,因为write会更改文件偏移指针
if (lseek(fd, 0, SEEK_SET) == -1)
{
printf("lseek err\n");
return;
}
if (read(fd, buf_to_read, 30) == -1)
{
printf("read err\n");
return;
}
printf("read: %s\n", buf_to_read);
exit(0);
}
编译命令:gcc ioexample.c
编译成功后运行:./a.out
结果:自己试去吧。
水平有限,如果有朋友发现错误,欢迎留言交流。
转载请保留本文链接,如果觉得我的文章能帮到您,请顶一下。,谢谢。
还没有评论,来说两句吧...