When I want to redirect an output of a.out program I will use

./a.out > output.txt

This doesn't work when the program reads something from stdin. How would you redirect output in this case?

I can do it only with

./a.out < inputs.txt > output.txt

Can I do the same but reading inputs from stdin?

EDIT: I realized that it works, but I can't see prompts because everything goes to file output.txt. So, the only problem is to see prompts on stdin and preserve redirection at the same time.

  • 1
    I'm not a developer, so I'm not sure about convention, but don't prompts go to STDERR typically? Alternatively, you can use the tee command, something like ./a.out |tee output.txt – cjc May 27 '12 at 11:42
  • Tee is good but I can't see the prompts (printf statement in C) at the right moment. – xralf May 27 '12 at 12:39
  • @cjc no prompts typically go to stdout. But xralf can check if stdout is a terminal and if it is not a terminal print the prompt to stderr – Ulrich Dangel May 27 '12 at 17:40
  • 1
    If the prompts are sent to the same channel as the normal output, your program doesn't support what you're trying to do; it's probably badly designed. You would need to use a wrapper to filter the output between prompt and non-prompt. Use expect. – Gilles May 27 '12 at 23:42

One option would be to write your prompts to stderr rather than stdout. They'll be visible on the terminal but not in output.txt.

Another option is not to use redirection for your output but take an output filename as a parameter and open that file yourself. You can then use stdout for your prompts. (This is more flexible. You can decide what goes only to the file, what goes only to the screen, and potentially what goes to both.)

If you can't change the code, the only option is to use tee or some other such utility. Buffering can be a problem; stdbuf might help with that.

  • I'd like to rather don't change the application. Assume I have only binary (if it's even possible, maybe it's not possible). – xralf May 27 '12 at 12:40
  • Modifying the code is better. If you only have the binary, why did you tag this c, and why is your binary called a.out? cjc already gave you an option without modifying the code (inserted above too), that's pretty much all you have as options. – Mat May 27 '12 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.