Duplicate, but still use stdout
A simple call to dup
will perform the saving. Here is a working example:
#include <stdio.h>#include <unistd.h>#include <fcntl.h>int main(){ // error checking omitted for brevity int original_stdout = dup(1); // magic int fd = open("foo", O_WRONLY | O_CREAT); dup2(fd, 1); close(fd); // not needed any more write(1, "hello foo\n", 10); // goes to the file open on fd write(original_stdout, "hello terminal\n", 15); // still goes to the terminal return 0;}