OSX is a POSIX systems, and like all POSIX systems standard output is file descriptor STDOUT_FILENO
(which is a macro defined as 1
).
What you can do is duplicate STDOUT_FILENO
to another file descriptor, open a temporary file and duplicating (using dup2
) the temporary file as STDOUT_FILENO
. Then whenever there is output to standard out (using plain write
, C printf
or C++ std::cout
) it will be put in the temporary file.
When done with the temporary "redirection" you simply duplicate the saved standard output (from the first dup
call) back into STDOUT_FILENO
. and close and remove the temporary file.
Something like the following:
int saved_stdout = dup(STDOUT_FILENO);
int temp_file = open("/tmp/temp_stdout", O_WRONLY, 0600);
dup2(temp_file, STDOUT_FILENO); // Replace standard out
// Code here to write to standard output
// It should all end up in the file /tmp/temp_stdout
dup2(saved_stdout, STDOUT_FILENO); // Restore old standard out
close(temp_file)
unlink("/tmp/temp_stdout"); // Remove file