标准输入输出重定向

来源:百度文库 编辑:神马文学网 时间:2024/04/28 06:38:33
//#include
//#include
#include
#include
#include
//#include
int main(void)
{
#define STDOUT 1
int nul, oldstdout;
char msg[] = "This is a test\n";
char msg_in[]="stdin\n";
/* create a file */
nul = open("DUMMY.FIL", O_CREAT | O_RDWR);
/* create a duplicate handle for standard
output */
oldstdout = dup(STDOUT);
/*
redirect standard output to DUMMY.FIL
by duplicating the file handle onto the
file handle for standard output.
*/
dup2(nul, STDOUT);
dup2(nul, 0);
dup2(nul, 2);
/* close the handle for DUMMY.FIL */
close(nul);
/* will be redirected into DUMMY.FIL */
write(STDOUT, msg, strlen(msg));
write(0,msg_in,strlen(msg_in));
/* restore original standard output
handle */
dup2(oldstdout, STDOUT);
/* close duplicate handle for STDOUT */
close(oldstdout);
return 0;
}