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

结果:自己试去吧。


水平有限,如果有朋友发现错误,欢迎留言交流。
转载请保留本文链接,如果觉得我的文章能帮到您,请顶一下。,谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值