/* 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;
}