How do I determine if a terminal is color-capable?

后端 未结 3 860
说谎
说谎 2020-12-08 10:02

I would like to change a program to automatically detect whether a terminal is color-capable or not, so when I run said program from within a non-color capable terminal (say

3条回答
  •  盖世英雄少女心
    2020-12-08 10:33

    You almost had it, except that you need to use the lower-level curses function setupterm instead of initscr. setupterm just performs enough initialization to read terminfo data, and if you pass in a pointer to an error result value (the last argument) it will return an error value instead of emitting error messages and exiting (the default behavior for initscr).

    #include 
    #include 
    
    int main(void) {
      char *term = getenv("TERM");
    
      int erret = 0;
      if (setupterm(NULL, 1, &erret) == ERR) {
        char *errmsg = "unknown error";
        switch (erret) {
        case 1: errmsg = "terminal is hardcopy, cannot be used for curses applications"; break;
        case 0: errmsg = "terminal could not be found, or not enough information for curses applications"; break;
        case -1: errmsg = "terminfo entry could not be found"; break;
        }
        printf("Color support for terminal \"%s\" unknown (error %d: %s).\n", term, erret, errmsg);
        exit(1);
      }
    
      bool colors = has_colors();
    
      printf("Terminal \"%s\" %s colors.\n", term, colors ? "has" : "does not have");
    
      return 0;
    }
    

    Additional information about using setupterm is available in the curs_terminfo(3X) man page (x-man-page://3x/curs_terminfo) and Writing Programs with NCURSES.

提交回复
热议问题