1 回答

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
fflush(stdout);
setvbuf(stdout,NULL,_IONBF,0);
printf("test stdout\n");
int save_fd = dup(STDOUT_FILENO); // 保存標(biāo)準(zhǔn)輸出 文件描述符 注:這里一定要用 dup 復(fù)制一個(gè)文件描述符. 不要用 = 就像是Winodws下的句柄.
int fd = open("test1.txt",(O_RDWR | O_CREAT), 0644);
dup2(fd,STDOUT_FILENO); // 用我們新打開的文件描述符替換掉 標(biāo)準(zhǔn)輸出
printf("test file\n");
//再恢復(fù)回來標(biāo)準(zhǔn)輸出. 兩種方式
//方法1 有保存 標(biāo)準(zhǔn)輸出的情況
//dup2(save_fd,STDOUT_FILENO);
//方法2 沒有保存 標(biāo)準(zhǔn)輸出的情況
int ttyfd = open("/dev/tty",(O_RDWR), 0644);
dup2(ttyfd,STDOUT_FILENO);
printf("test tty\n");
}
添加回答
舉報(bào)