0

I want to still be able to write in C++ to the terminal (to show a progress report) even when my program is redirected using a pipe in bash by the user, like for example with the command:

myprogram | sort

Is there a way to this?

jww
  • 97,681
  • 90
  • 411
  • 885
programmer
  • 41
  • 6
  • 1
    Write to `cerr` or `stderr`. Those aren't redirected (in the situation described). – john Jul 25 '19 at 05:14
  • This is an option but I want a solution that would work even if the user also redirect to cerr or stderr – programmer Jul 25 '19 at 05:16
  • 1
    If you are writting to the streams. To you it is a stream where it goes depends on where the parent processes directs it (usually the console). If you want to bypass the stream mechanism you need to find some other visualization library. Have a look at `ncurses`. This will require you to create a window to draw your text into (but its not that difficult). – Martin York Jul 25 '19 at 05:31
  • 1
    This is usually not something you do for users. You output to stdout or stderr as expected. It is up to the user to redirect the output; or `tee` to see the output and redirect to a file. Also see [How to redirect output to a file and stdout](https://stackoverflow.com/q/418896/608639) and friends. – jww Jul 25 '19 at 06:09

2 Answers2

0

You cannot and should not try to control how the user wants to process the output of your program. You should strive to use the standard streams with the best of intentions.

  1. Write informational messages to std::cout/stdout.
  2. Write error/warning messages to std::cerr/stderr.

If the user wishes to see the output of your program while still being able to save the output to a file, they may use tee.

program | tee filename
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • I am not really trying to control how the user wants to process the output. I just want to show a progress report line while the program executes that I will erase when the program terminates. Thus it won't interfere with the user intents with his redirection. I thought perhaps with dup/pipe i might find a way perhaps i didn't find any. Is there a way perhaps using termios to access the terminal directly? – programmer Jul 25 '19 at 12:29
  • @programmer, that's an idea. I don't have any experience in that subject. You could try it. Best of luck. – R Sahu Jul 25 '19 at 16:04
0

I have found an answer.

int fd = open(ctermid(NULL), O_WRONLY);
std::string text("hello my terminal!);
write(fd, text.c_str(), text.size());
close(fd);

This works perfectly even if stdin, stdout and stderr have been redirected!

programmer
  • 41
  • 6