Learning C, Day 3

I spent about 3 hours today learning C. I found an excellent blog with C tutorials: flaviocopes.com

I also cobbled together a text colorizing program for Windows. Windows Batch can’t print colored text without changing the already printed text, but this program can do that. I’m at the point of being able to copy and paste from stackoverflow, so I guess I’m 70% an experienced C developer now xD

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

/************************************************************************************************\
*                                                                                                *
*  Sources:                                                                                      *
*      stackoverflow.com/a/8765974                                                               *
*      stackoverflow.com/a/10156436                                                              *
*      docs.microsoft.com/en-us/windows/console/using-the-high-level-input-and-output-functions  *
*                                                                                                *
\************************************************************************************************/

CONSOLE_SCREEN_BUFFER_INFO info;
HANDLE hConsole;
WORD wOldColorAttrs;
int colorNumber;

int main(int argc, char * argv[]) {
	hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	
	if ((argc<3) || (! GetConsoleScreenBufferInfo(hConsole, &info))) { // Error checking.
		return 1;
	}
	wOldColorAttrs = info.wAttributes; // Save the old color.
	colorNumber=(int)strtol(argv[1], NULL, 16); // Convert the hexadecimal color command line argument to an integer.
	
	SetConsoleTextAttribute(hConsole, colorNumber); // Set the new color.
	printf("%s",argv[2]);
	SetConsoleTextAttribute(hConsole, wOldColorAttrs); // Restore the old color.
	
	return 0;
}

Usage: colors.exe 0f “Colors!”

In the windows command prompt, see “color /?” for color options.

Or string together multiple calls: the program doesn’t add a new line to the output.

See you tomorrow!

Leave a comment

Your email address will not be published. Required fields are marked *

Your data is processed in accordance with my privacy policy. Comments are manually approved and may take a while to appear.