Introduction
While working with console applications, sometimes we want to print coloured error messages. Here is the implementation of a very small function which will help in accomplishing the task.
int _teprintf(TCHAR *format, ...)
{
HANDLE hStdOut = NULL ;
TCHAR szBuffer[1024] ;
va_list arg_list ;
int nBuf = 0 ;
va_start(arg_list,format);
nBuf = _vsntprintf(szBuffer,1024,format,arg_list) ;
va_end(arg_list) ;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if(!hStdout) {
return 0;
}
if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED |
FOREGROUND_INTENSITY)) {
return 0;
}
nBuf = _tprintf(_T("%s"),szBuffer) ;
if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED |
FOREGROUND_BLUE |
FOREGROUND_GREEN)) {
return 0;
}
return nBuf ;
}
You can use it as follows:
int _tmain(int argc, _TCHAR* argv[])
{
_teprintf(_T("\nI am Error\n")) ;
_tprintf(_T("\nI am Normal\n")) ;
return 0;
}
Though this is trivial, it is fun..!
History
- 5th December, 2006: Initial post