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?
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?
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.
std::cout
/stdout
.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
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!