我注意到我的程序使用函数 popen 并重新分配标准输出因 printf 函数而失败
编码:
# include <stdio.h>
int main(int argc, char * argv[])
{
FILE * tmp = stdout;
char * command = "cat > newfile.txt";
double a=12.2344;
stdout = popen( command, "w"); /* permitted according to glibc tutorial */
printf("That was laddy\n"); /* This doesn't go to newfile.txt !!!*/
fprintf(stdout, "And his lass\n"); /* but This goes */
/* but this...... */
printf("A double number: %.2f\n", a); /* unexpectedly goes where the
first printf hasn't gone */
/* is it a bug or there is something wrong in a code ? */
pclose(stdout);
stdout = tmp;
return 0;
}
函数 printf 有什么用?一次它在 tty 上打印,但下一次是文件“newfile.txt”(它应该在哪里)。是 glibc 的错误还是上面代码中的错误。我在我的实用程序中使用该重定向。感谢您的任何建议。