I use GCC on Ubuntu 18.04.
I want the text to be a different color.
For example:
printf("hello world");
I tried using conio.h but the compiler gives me an error that conio.h is not available. how can I achieve it?
I use GCC on Ubuntu 18.04.
I want the text to be a different color.
For example:
printf("hello world");
I tried using conio.h but the compiler gives me an error that conio.h is not available. how can I achieve it?
<conio.h>
is typical for Windows. In Linux, you put some control codes in your string.
Most of sources describe how to do that in bash (like this one How to change the output color of echo in Linux), but you can easlly use it in C. So first you can use hexdump to get how sequence in bash translate to string:
$ echo -e "\033[0;31m" foo #this print foo in red
foo
$ echo -e "\033[0;31m" foo | hexdump -C
00000000 1b 5b 30 3b 33 31 6d 20 66 6f 6f 0a |.[0;31m foo.|
0000000c
As you can see, just first part has to be changed to binary code 0x1b.
Finaly I write code in C:
#include <stdio.h>
int main () {
printf("%c[0;31mFOO\n", 0x1b);
return 0;
}
And it prints FOO in red. Actually it doesn't change color back, but I don't care because I have a color prompt. :)
Terminals are usually (even on Windows) controlled by Ansi Escape codes. You can use them to control the output color, or the location of the cursor. See: How to make win32 console recognize ANSI/VT100 escape sequences? and https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences