Dup2 which copies instead of redirects

I have the following at the beginning of my code to redirect stdout to a file. Instead of redirecting lines sent to stdout to a file, I want lines to be sent to both stdout and the file. How can I do this from my code?

int main(int argc, char** argv)
{
    int file = open("out.txt", O_APPEND | O_WRONLY);
    if(file < 0)    return 1;
    if(dup2(file,1) < 0)    return 1;
    ...
}

      

UPDATE

Please not that my code is using printf and other c functions to write to stdout.

+3


source to share


2 answers


Open the pipe to tee

, then write on it.

// be careful to quote the file argument properly!
FILE *fp = popen("tee out.txt", "w");

      



You cannot get the behavior you want at the file descriptor level or stdio level on a POSIX system.

+3


source


If you want it to work with printf

, I can only see two possibilities: either print to stdout only, or use a utility tee

to also write everything to a file from the outside, or write a wrapper around printf

which calls printf

twice, once to write to the file and once to write to stdout (and for every other c function you use in your code to print to stdout). You cannot do what you want using only dup

/ dup2

.



0


source







All Articles