dup/dup2输出重定向

本文介绍了如何使用dup和dup2函数实现文件描述符的重定向,通过实例展示了将标准输出重定向到文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时我们希望把标准输入重定向到一个文件,或者把标准输出重定向到一个网络连接。

dup()与dup2()能对输入文件描述符进行重定向。

int dup(int oldfd);

int dup2(int oldfd, intnewfd);

dup函数创建一个新的文件描述符,该新文件描述符和原有文件描述符oldfd指向相同的文件、管道或者网络连接。

并且dup返回的文件描述符总是取系统当前可用的最小整数值。dup2和dup类似,不过它将返回第一个不小于oldfd的整数值。dup和dup2失败时返回-1并设置errno。

1.打开一个新文件

2.关掉标准输出文件符

3.调用dup给文件描述符

4.此时文件描述符变为1

5.将所要打印数据重定向到文件中


dup函数:

/*************************************************************************
	> File Name: dup.c
	> Author: fucang_zxx
	> Mail: fucang_zxx@163.com 
	> Created Time: Thu 28 Jul 2016 04:15:35 PM CST
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>

int main()
{
	//打开一个文件
	int fd = open("./log", O_CREAT | O_RDWR, 0644);
	if(fd < 0)
	{
		perror("open");
		return 1;
	}
	//关闭标准输出文件描述符
	close(1);

	//进行重定向
	int new_fd = dup(fd); //new_fd = 1
	if(new_fd < 0)
	{
		perror("dup");
		return 2;
	}
	close(fd);

	char buf[1024];
	while(1)
	{
		memset(buf, '\0', sizeof(buf));
		ssize_t _s = read(0, buf, sizeof(buf) - 1);
		if(_s <  0)
		{
			perror("read");
			return 3;
		}
		else
		{
			buf[_s] = '\0';
		}
		if(strncmp("quit", buf, 4) == 0)
		{
			//退出
			break;
		}
		printf("%s", buf); //将往文件中写入
		fflush(stdout); //必须做,因为重定向后printf函数将由行缓冲变为全缓冲
		sleep(1);
	}
	close(new_fd);
	return 0;
}




dup2函数:

/*************************************************************************
	> File Name: dup2.c
	> Author: fucang_zxx
	> Mail: fucang_zxx@163.com 
	> Created Time: Thu 28 Jul 2016 04:56:35 PM CST
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>

int main()
{
	//打开一个文件
	int fd = open("./log", O_CREAT | O_RDWR, 0644);
	if(fd < 0)
	{
		perror("open");
		return 1;
	}
	//关闭标准输出文件描述符
  //  close(1);  //dup2不需要手动关闭,系统会自动关闭

	//进行重定向
	int new_fd = dup2(fd, 1); //new_fd = 1
	if(new_fd < 0)
	{
		perror("dup2");
		return 2;
	}
	close(fd);

	char buf[1024];
	while(1)
	{
		memset(buf, '\0', sizeof(buf));
		ssize_t _s = read(0, buf, sizeof(buf) - 1);
		if(_s <  0)
		{
			perror("read");
			return 3;
		}
		else
		{
			buf[_s] = '\0';
		}
		if(strncmp("quit", buf, 4) == 0)
		{
			//退出
			break;
		}
		printf("%s", buf); //将往文件中写入
		fflush(stdout); //必须做,因为重定向后printf函数将由行缓冲变为全缓冲
		sleep(1);
	}
	close(new_fd);
	return 0;
}




### DUP2 函数用于输出重定向Linux 环境下,`dup2()` 是一个重要的系统调用函数,主要用于复制文件描述符并将其绑定到指定的目标文件描述符上。这使得程序能够方便地实现标准输入/输出重定向。 具体来说,在执行 `int dup2(int oldfd, int newfd)` 后: - 如果 `newfd` 已经存在,则先关闭它。 - 将 `oldfd` 的副本赋给 `newfd`,即让两者共享同一个内核级文件表项。 - 这样一来,任何针对 `newfd` 的读写操作实际上都会作用于原先由 `oldfd` 所指向的那个实际文件对象之上[^1]。 #### 实现输出重定向的例子 下面是一个简单的例子展示如何利用 `dup2()` 来改变标准输出的方向至另一个文件: ```c #include <stdio.h> #include <unistd.h> // For close(), dup2() #include <fcntl.h> // For open() int main(){ // 创建或打开名为 "output.txt" 文件准备写入 int file_desc = open("output.txt", O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR); if (file_desc == -1){ perror("Failed to create/open output.txt"); return 1; } // 使用 dup2 把 stdout(通常是屏幕) 改成我们的新文件 if(dup2(file_desc, STDOUT_FILENO)==-1){ perror("Error redirecting standard out."); close(file_desc); return 1; } // 关闭原始文件描述符以防泄露资源 close(file_desc); printf("This message should go into 'output.txt'.\n"); return 0; } ``` 这段代码会将所有的后续打印语句的结果都保存到 `"output.txt"` 中而不是显示在屏幕上。这是因为通过调用 `dup2()` ,已经成功地把原本的标准输出流 (`stdout`) 替换成了指向 `"output.txt"` 的文件描述符。 #### 处理错误情况 需要注意的是,在使用 `dup2()` 前应该始终检查返回值以确认操作是否成功完成;如果失败则通常意味着参数非法或是权限不足等问题发生。此外,当不再需要某个已打开的文件时记得及时关闭对应的文件描述符以免造成不必要的资源浪费。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值