Write to two files using only one file descriptor

This is a discussion on Write to two files using only one file descriptor within the C Programming forums, part of the General Programming Boards category; The problem I am facing is the need to write to stdout and to another file. I want the output ...

Write to two files using only one file descriptor

The problem I am facing is the need to write to stdout and to another file. I want the output to be displayed on the screen and into the file. This program is similar to the script command already available, but it is very simplified.

Anyway. So far I have found it simple to write to two file descriptors going to place (dup/dup2) but what I want to do is the opposite.

So, like this:
--<==
not like this:
==>--.

Make sense?

I don't have any code yet, as I am solving the problem before I start to code.

Note that you CAN NOT write to different targets with one filedescriptror. One filedescriptor connects to exactly one fileobject [unless it's a closed filedescriptor, in whcih case it's not connected to any fileobject].

The only real solution if you don't want to use tee is that you create a function like this:

Basically, I am writing a simple shell. So the output from the commands entered into the shell (such as cp, rm, mv) would go to stdout and to the file. Also, stdin would be read into the program and into the file, though that would be easier.

I was hoping to do this (simplified psuedocode):

Code:

if tracing
set stdout to output to file and stdout //the hard part
call executeCommand(command to be executed) //does all the exec() work
end if

That being said, however, the assignment specifications do not specifically state that I have to output everything to the terminal.

If I do not output to terminal, I think I could dup2(file, fileno(stdout)) and be done with it. What do you think of that?