I read about freopen to redirect all printf to a file, but I would like the output to be printed on the screen as well. Is there an easy way to redirect the printfs to a file and get the cmd line output?
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
From outside the program, use “tee”:
In fact, you could popen() a channel to a tee that writes the file, though that’s system-heavy. Something to this effect:
I’m curious to see if there’s a from-C quick way of doing this, because at some level, this involves copying data. It’s easy to get two filehandles to write to the same place, use dup() or the like, but the opposite is more tricky. It might involve pushing a module (the common example is “connld” onto a stream), though honestly I’ve never seen this used, so I’d love to see a working code sample myself.
Best reference I can give is “Advanced Programming in the UNIX Environment” by Stevens.
Update:
To speak to R’s comment below, the above solution is a slightly heavier version of just fork/exec-ing and redirecting the child’s handle someplace else. Both will solve the problem, though I prefer the above because it’s easier to clean up, but honestly, both solutions are pretty heavy. Fork() is no lightweight function. If the spirit of the question is to do so without fork/exec, then I’m not sure, I’d love to know, too. If fork/exec is okay, then directly using it or using popen() will hack it.