出處:http://blog.csdn.net/eqxu/article/details/1641842
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
#define STDOUT 1 //標準輸出文件描述符號
{
#define STDOUT 1 //標準輸出文件描述符號
int nul, oldstdout;
char msg[] = “This is a test”;
char msg[] = “This is a test”;
/* create a file */
//打開一個文件,操作者俱有讀寫權限如果文件不存在就創建
nul = open(“DUMMY.FIL”, O_CREAT | O_RDWR,
S_IREAD | S_IWRITE);
nul = open(“DUMMY.FIL”, O_CREAT | O_RDWR,
S_IREAD | S_IWRITE);
/* create a duplicate handle for standard
output */
output */
//創建STDOUT的描述符備份
oldstdout = dup(STDOUT);
/*
redirect standard output to DUMMY.FIL
by duplicating the file handle onto the
file 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.
*/
//重定向nul到STDOUT
dup2(nul, STDOUT);
dup2(nul, STDOUT);
/* close the handle for DUMMY.FIL */
//重定向之後要關閉nul
close(nul);
close(nul);
/* will be redirected into DUMMY.FIL */
//寫入數據
write(STDOUT, msg, strlen(msg));
write(STDOUT, msg, strlen(msg));
/* restore original standard output
handle */
handle */
//還原
dup2(oldstdout, STDOUT);
dup2(oldstdout, STDOUT);
/* close duplicate handle for STDOUT */
close(oldstdout);
close(oldstdout);
return 0;
}
}
//結果就是msg寫到了文件中而不是STDOUT