The user laalto is right, but on Linux, the function you are looking for is called fopencookie
. Fixing the laalto example for Linux results in:
int my_writefn(void *cookie, const char *data, int n) { FILE **files = (FILE **)cookie; fwrite(data, n, 1, files[0]); return fwrite(data, n, 1, files[1]); } int noop(void) { return 0; } cookie_io_functions_t my_fns = { (void*) noop, (void*) my_writefn, (void*) noop, (void*) noop }; FILE *files[2] = ...; FILE *f = fopencookie((void *)files, "w", my_fns);
When you write to f
, the system will execute your function my_writefn
, passing it the data that was passed to fwrite
. To simplify the task, you can also change the buffering for the line-oriented file stream:
setvbuf(f, NULL, _IOLBF, 0);
This will buffer the data passed to fwrite
until a new line is output, or any data is read from any process-related stream (e.g. stdin). NOTE: you must call sevbuf
after fopencookie
, but before writing any data to the stream.
I use line buffering because I usually use fopencookie
to redirect stderr to syslog or through a network socket, and the processing-oriented data is simpler and more efficient.
source share