Here is my code for printf()
implementation in C. Please share your thoughts for improvements.
#define PRINTCHAR(c) putchar(c)
#define MAXLEN 256
// Write a printf function which simulates printf() in C.
int formatAndPrintString(char *pcFmt, va_list lList)
{
//Holds the number of characters printed, 0 on error
int nChars = 0;
while(*pcFmt != '\0')
{
if(*pcFmt == '%')
{
pcFmt++;
int iTemp = 0;
char acTemp[MAXLEN] = "";
char *pcTemp = NULL, cTemp = 0;
switch (*pcFmt)
{
case 'd':
iTemp = va_arg(lList, int);
itoa(iTemp, acTemp, 10);
for(int i = 0; i < strlen(acTemp); i++)
{
PRINTCHAR(acTemp[i]); nChars++;
}
break;
case 's':
pcTemp = va_arg(lList, char*);
while(*pcTemp != '\0')
{
PRINTCHAR(*pcTemp); nChars++;
pcTemp++;
}
break;
case 'c':
cTemp = va_arg(lList, int);
PRINTCHAR(cTemp);
nChars++;
break;
default:
break;
}
pcFmt++;
}
else
// print the char to console
{
PRINTCHAR(*pcFmt);
pcFmt++; nChars++;
}
}
return nChars;
}
// Print function identical to printf() in stdio.h
int printfunc(char *pcFormat, ...)
{
if(!pcFormat)
{
return 0;
}
va_list lList;
va_start(lList, pcFormat);
return(formatAndPrintString(pcFormat, lList));
}