问题
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