dup,dup2实现stdout重定向

/* dup,dup2实现stdout重定向 */
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(void)
{
	int fd, tempfd;
	char buf[] = "Am I in the stdout or in the file?\n";
	if( (fd = open("tempfile", O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1 )
	{
		perror("open file error");
		exit(1);
	}
	/* 保存STDOUT_FILENO文件描述符 */
	if( (tempfd = dup(STDOUT_FILENO)) == -1 )
	{
		perror("dup error");
		exit(1);
	}
	/* 使文件描述符1——STDOUT_FILENO指向tempfile */
	if(dup2(fd, STDOUT_FILENO) == -1)
	{
		perror("dup2 error");
		exit(1);
	}
	printf("printf:I am also in stdout!\n");	/* printf()并没有输出到文件,而且是在程序结束时输出的屏幕的,因为标准I/O缓冲区的缘故 */
	if( write(STDOUT_FILENO, buf, strlen(buf)) == -1 )	/* 注意write()的长度 */
	{
		perror("write error");
		exit(1);
	}
	/* 还原STDOUT_FILENO */
	if(dup2(tempfd, STDOUT_FILENO) == -1)
	{
		perror("dup2 error");
		exit(1);
	}
	close(fd);
	close(tempfd);	/* tempfd指向stdout,所谓关闭文件,并不是真正的“关闭”文件 */
	char tempstr[] = "just test if I am in stdout.\n";
	if( write(STDOUT_FILENO, tempstr, strlen(tempstr)) == -1 )
	{
		perror("write error");
		exit(1);
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值