我有一個奇怪的問題,使用dup2系統調用將STDOUT重定向到一個文件。奇怪的問題重定向輸出使用dup2系統調用
我使用的是2個功能,我發現在這裏: In C how do you redirect stdin/stdout/stderr to files when making an execvp() or similar call?
下面是一個簡單的程序,我寫來測試功能後,我有錯誤。 程序按預期工作並將輸入寫入文件。
int fd;
fpos_t pos;
int main(){
while(1){
char input[100];
printf("Please enter text: ");
gets(input);
printf("\nString = %s\n", input);
switchStdout("test.txt");
puts("THIS TEXT SHOULD REDIRECT\n");
printf("String(file) = %s\n", input);
revertStdout();
puts("This should come before the gets() ??\n");
}
return 0;
}
void switchStdout(const char *newStream)
{
fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
freopen(newStream, "w", stdout);
return;
}
void revertStdout()
{
fflush(stdout);
dup2(fd, fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos);
}
調用revertStdout()函數後,程序似乎掛起。
我意識到,事實上,程序在打印之前調用了gets()「這應該在gets()??之前出現」
輸入文本後,程序打印跳過的行。
下面是我在大膽進入終端輸出:
請輸入文字:你好!!!!
String = Hello !!!!
爲什麼我能夠在此輸入?
這應該在gets()之前?請輸入文字:
String =爲什麼我能夠在此輸入?
對不起,很長的職位。程序按預期寫入文件。
感謝任何人都可以提供的幫助。
http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used –
如果你想重新打開一個流來使用一個不同的描述符或句柄,你可能需要'fdopen()'。它不在標準庫中,但Unix,Windows和OSX都支持它。 – Davislor