问题描述
我的 C 程序预计会产生大量输出.
My C program is expected to produce a lot of output.
其中一些输出行是特殊的,我想将副本写入特殊文件.我结束了
Some of these output lines are special and I would like to write a copy to a special file. I end up doing
FILE * outf = fopen("special_file", "a");
fprintf(stdout, "normal line 1\n");
fprintf(stdout, "special line!\n");
fprintf(outf, "special line!\n");/*inelegant & dangerous code duplication*/
fprintf(stdout, "normal line 2\n");
有没有一种简单的方法可以避免这种不雅的&危险的代码重复?我有很多这样的东西,我最终可能会写出像 printf("next is %d\n", num++);
这样的东西,这些东西不能天真地复制,例如使用宏.
Is there an easy way to avoid such inelegant & dangerous code duplication? I have quite a lot of it and I may eventually write things like printf("next is %d\n", num++);
that cannot be duplicated naively, e.g. using macros.
目前我认为除了生成一个将运行 tee
等效项的子进程之外,没有其他解决方案.还有其他想法吗?例如.可以定义一种 FILE*
以某种方式重定向到 stdout
&outf
?
At the moment I see no solution short of spawning a child process that will run a tee
equivalent. Any other idea? E.g. can one define a kind of FILE*
that will in some way redirect to both stdout
& outf
?
推荐答案
我认为 dup(2) 系统调用是您所需要的,请参阅man 2 dup".
I think the dup(2) system call is what you need, see "man 2 dup".
感谢投票,但我想我错了.
edit: thanks for the votes, but I think I got it wrong.
dup 的作用是让两个文件描述符引用一个文件.您想要的是一个引用两个文件的类似文件描述符的对象.那是完全不同的事情.
What dup does is make two file descriptors reference one file. What you want is a single file descriptor-like object that references two files. That's quite a different thing.
这篇关于fprintf 到文件和标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!