4

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?

Community
  • 1
  • 1
Abhinav Gauniyal
  • 7,034
  • 7
  • 50
  • 93
  • `unistd.h` is a POSIX header, which is entirely orthogonal to the C and C++ standards. I don't think either of those standards has any notion of a terminal, so you have little choice but to depend on system APIs for system-specific functionality. – melak47 Jan 01 '16 at 17:43
  • Related: http://stackoverflow.com/questions/15331566/c-include-unistd-h-why-not-cunistd . – David Hammen Jan 01 '16 at 19:19

1 Answers1

5

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
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • pipes & redirects == bash's `|` and `>` ? and what is VT100? my knowledge is limited to tty,pty,shells and gui-terminals :( – Abhinav Gauniyal Jan 01 '16 at 17:52
  • 2
    You should use the termcap library to get escape sequences, rather than hard-coding the sequences for a particular terminal. But all modern terminal emulators use sequences based on VT100 terminal from the 70's. – Barmar Jan 01 '16 at 18:04
  • @AbhinavGauniyal [Wikipedia is your friend](https://en.wikipedia.org/wiki/VT100) :) – Some programmer dude Jan 01 '16 at 18:07
  • @Barmar I am currently reading about terminfo, and I guess I should be using this over termcap, right? Users report terminfo part working in OSX too. – Abhinav Gauniyal Jan 01 '16 at 18:17