tags:

views:

248

answers:

4

Is there a way to to couple two streams (or file descriptors) together so that writing to one stream will also write to the second one? (C, Linux)

Thanks.

+1  A: 

You can implement something similar to functionality of tee with boost::iostreams.

stefanB
Do you have an example for C? Because that is strictly C++ ;)
Skurmedel
sorry probably not
stefanB
+1  A: 

Not sure if it's what you want, but 'tee' in unix does something similar.

Rich Bradshaw
So the "C++" guy gets modded up, but you get modded down for suggesting to "build on the work of others". That's not right...
Roboprog
+3  A: 

The first thing that came to mind to me was also "tee". So, let's combine C and the shell with popen:

FILE * multi_out;

multi_out = popen( "tee file1.out > file2.out", "w");
/* error checks, actual work here */
pclose( multi_out);
/* error checks here */

As a Unix bigot, I have assumed you are not trying this on Windows.

Roboprog
Ah, you said "Linux". Good boy :-)
Roboprog
+3  A: 

Use funopen or fwopen and supply your own write function that writes to multiple FILE*s.

Example:

FILE *files[2] = ...;

FILE *f = fwopen((void *)files, my_writefn);

// ... use f as you like ...

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]);
}

(Error handling omitted.)

Note that funopen and fwopen are BSD and not in standard Linux. I'm not aware if there's a Linux-compatible equivalent.

laalto
Apparently, no. They are not in man pages (at least on my system).
Jack
funopen is on BSD and Mac OS X. On Linux use fopencookie.
mark4o
@mark4o: Thanks for the info. @Jack: Seems like the implementation using fopencookie() would be quite similar. Not updating my answer here but you should have some pointers to go forward with.
laalto
This saves computer time. I'm not sure it saves programmer time. Neat trick, though (even if not completely portable, where portable = "among unices").
Roboprog