【发布时间】:2017-04-03 21:05:51
【问题描述】:
我在使用 dup2 系统调用将 STDOUT 重定向到文件时遇到了一个奇怪的问题。
我正在使用在这里找到的 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()函数后,程序出现挂起。
我意识到,事实上,程序在打印“This should come before the gets() ??”之前调用了gets()
在我输入文本后,程序会打印跳过的行。
这里是终端输出,我用粗体输入:
请输入文字:Hello!!!!
String = 你好!!!!
为什么我可以在这里打字??
这应该出现在 gets() 之前??请输入文字:
String = 为什么我可以在这里输入??
抱歉,帖子太长了。程序按预期写入文件。
感谢任何人提供的任何帮助。
【问题讨论】:
-
如果您想重新打开流以使用不同的描述符或句柄,您可能需要
fdopen()。它不在标准库中,但 Unix、Windows 和 OSX 都支持。