2

When I ran this command on linux $ gcc, it gave me an output like this:

gcc: fatal error: no input files compilation terminated. 

Where, gcc was in bold white color and fatal error: was in bold red color.

And then I ran this command $ gcc &> err.txt and the content of err.txt was:

gcc: fatal error: no input files compilation terminated. 

With no ANSI color codes, just the plain text.

But with my program written in C++, the text file's content was:

[1;91merr:[0m no arguments were passed, try using '--help' 

Where err: was in bold red color with showed up in terminal but the file too contains those characters.

My sample code is:

if (argc == 1) { std::fprintf(stderr, "\033[1;91merr:\033[0m no arguments were passed, try using '--help'\n"); return EXIT_FAILURE; } 

My Question:

  1. How does gcc and other linux programs prints colored text on terminal without using ANSI color codes?
  2. Are there any other methods to print colored output on terminal except ANSI color codes?
  3. Are there any cross-platform libraries todo so?
9
  • 2
    gcc is using ANSI escape sequences; it's just omitting them when it thinks its output is being redirected into a file instead of to an interactive terminal. Commented Aug 1, 2023 at 6:30
  • 3
    For POSIX systems it probably checks isatty to check if the standard output is connected to a terminal or something else (redirected, pipe, etc). Commented Aug 1, 2023 at 6:32
  • 1
    Unfortunately it's not really possible to check in a cross-platform way, unless you're using a library or emulation layer (e.g. Cygwin) that handles it for you. As for what GCC does on Windows and CMD I don't know, but the good news is that the source for GCC is freely available. The bad news is that the source is rather messy and it could be hard to find. Commented Aug 1, 2023 at 6:42
  • 1
    I think on Windows you need to use SetConsoleMode(... ENABLE_VIRTUAL_TERMINAL_PROCESSING). See stackoverflow.com/a/51777740/567292 Commented Aug 1, 2023 at 6:42
  • 2
    The equivalent of isatty on Windows is GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE)) or similar. See github.com/gcc-mirror/gcc/blob/… for how gcc does it. Commented Aug 1, 2023 at 6:43

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.