fprintf both to file and to stdout [duplicate]

大憨熊 提交于 2020-01-06 14:40:57

问题


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");

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.

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/27505134/fprintf-both-to-file-and-to-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!