Color console in ANSI C?

just plain ANSI C?

No. The C standard doesn't assume the stdout is a console or has color.

Can this be done in Windows, Linux, or Mac OS X?

Yes. See How can I print to the console in color on Mac OS X in a cross-platform manner? for Linux and Mac OS X.

For Windows, you may need to directly access the Console Functions if you want to avoid external libraries.


Yes, in Linux/ Mac it is possible using ANSI C89. You can either manipulate the font and the color of the text. using the following command:

printf("%c[0;00mHello, world!\n", 27); /* White color     */
printf("%c[1;33mHello, world!\n", 27); /* Yellowish color */
printf("%c[1;34mHello, world!\n", 27); /* Blueish color   */

Notice that the left part of the ";" (where the numbers 0, 1 are) manipulates the text font, the right part of ";" manipulates the colors. You can experiment on your own and find out new colors.

This code compiles using "-ansi -pedantic" command with no warnings nor errors.

***** Edit ***** In Windows based systems you can achieve colorful console text/background of text using the following example:

#include <stdio.h>
#include <windows.h>

int main(void)
{   
    /* Point to our console */
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    int i = 0;

    /* Iterate through colors */ 
    for(; i < 255; i++)
    { /* i stands for color type: could refer to actual text color or background color of text */
        SetConsoleTextAttribute(hConsole, i);
        printf("Colorful text");
    }

    getchar();
    return 0;
}

Good luck!

Tags:

C

Colors

Console