Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making sure program is in a terminal

I was trying to add colors to some strings that have to be displayed in a terminal using ansi escape code. So far I haven't grasped the whole ascii escapes code thing, just trying out by copy pasting some escape codes. Then saw this answer which asked to verify that program should check that its being executed in a terminal or else continue without polluting strings with escape codes?

Answer explains to use a *nix based function isatty() which I found out resides in unistd.h which in turn wasn't promoted to cunistd by cpp standard based on my understanding that it wasn't in c's standard at first place.I tried to search SO again but wasn't able to understand well. Now I have two questions regarding this :

  • In what environment(right word?) can a program - using ascii escape codes, be executed that it requires an initial check? since I'm bulding for cli only.
  • What would be a proper solution according to ISO cpp standards for handling this issue? using unistd.h? would this use confine to modern cpp practices?

Also is there anything I should read/understand before dealing with ansi/colors related thing?

like image 574
Abhinav Gauniyal Avatar asked Oct 16 '25 15:10

Abhinav Gauniyal


1 Answers

On a POSIX system (like Linux or OSX) the isatty function is indeed the correct function to determine if you're outputting to a terminal or not.

Use it as this

if (isatty(STDOUT_FILENO))
{
    // Output using VT100 control codes
}
else
{
    // Output is not a TTY, could be a pipe or redirected to a file
    // Use normal output without control codes
}
like image 127
Some programmer dude Avatar answered Oct 18 '25 05:10

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!