博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux --dup dup2 文件描述符重定向函数--输入输出重定向
阅读量:2351 次
发布时间:2019-05-10

本文共 846 字,大约阅读时间需要 2 分钟。

#include <sys/stat.h>

#include <string.h>
#include <fcntl.h>
#include <io.h>

int main(void)

{
#define STDOUT 1 //标准输出文件描述符 号

int nul, oldstdout;

char msg[] = "This is a test";

/* create a file */

//打开一个文件,操作者具有读写权限 如果文件不存在就创建

nul = open("DUMMY.FIL", O_CREAT | O_RDWR,S_IREAD | S_IWRITE);

/* create a duplicate handle for standard

output */

//创建STDOUT的描述符备份

oldstdout = dup(STDOUT);
/*redirect standard output to DUMMY.FILE by duplicating the file handle onto the file handle for standard output.*/

//重定向nul到STDOUT

dup2(nul, STDOUT);

/* close the handle for DUMMY.FIL */

//重定向之后要关闭nul

close(nul);

/* will be redirected into DUMMY.FIL */

//写入数据

write(STDOUT, msg, strlen(msg));

/* restore original standard output handle */

//还原

dup2(oldstdout, STDOUT);

/* close duplicate handle for STDOUT */

close(oldstdout);

return 0;

}

//结果就是msg写到了文件中而不是STDOUT

转载地址:http://zshvb.baihongyu.com/

你可能感兴趣的文章
C语言基础---数组、指针之间的相同与不同
查看>>
类的继承的应用场景
查看>>
python3 + selenium------Chrome和Firefox 驱动的使用和版本对应
查看>>
pycharm不同测试框架的设置、unittest测试案例
查看>>
python unittest TestCase间共享数据(全局变量的使用)
查看>>
Python中普通字符串 & json字符串&json对象的区别
查看>>
python中json.dumps()和json.dump() 以及 json.loads()和json.load()的区分
查看>>
Python3中打开文件的方式(With open)
查看>>
python中unittest加载测试用例的4种方法
查看>>
iOS中使用RNCryptor对资源文件加密
查看>>
Device Tree编译工具dtc
查看>>
softlockup/hardlockup原理详细介绍
查看>>
项目管理学习笔记之八风险管理过程总结
查看>>
项目管理学习笔记之九采购管理过程总结
查看>>
solaris常用命令总结
查看>>
邮件安全证书(S/MIME),如何申请邮件证书
查看>>
Go语言基础入门--简介
查看>>
Go语言基础入门--变量,类型
查看>>
Go语言基础入门--数组,切片,map
查看>>
Go语言基础入门--if,for,range,switch
查看>>