0

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?

Jongware
  • 22,200
  • 8
  • 54
  • 100
phs
  • 541
  • 3
  • 18
  • 1
    Put it in a function, which does both `fprintf` calls? – Some programmer dude Dec 16 '14 at 12:56
  • 2
    You can use vfprintf (tee like) or dup2. Have a look here: http://stackoverflow.com/questions/6420194/how-to-print-both-to-stdout-and-file-in-c – gj13 Dec 16 '14 at 12:59
  • 1
    About the use of `dup` (or similar functions), you can't have a file descriptor that references multiple files, at least not natively. Also, those functions are platform-specific, and not in the C standard. There might be platform-specific functions to allow it but the POSIX `dup` (and family) functions isn't it. – Some programmer dude Dec 16 '14 at 13:03
  • Thanks! This solves it. I did not realize that `vprintf` could implement a `tee` very easily. – phs Dec 16 '14 at 13:04

1 Answers1

2

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.

Mike Crawford
  • 2,232
  • 2
  • 18
  • 28