implementing printf()
How would i implement my own printf() ?
well, using stdarg.h we could create a function that can take any number of parameters. Then just parsing through each argument and writing it into standard output.
http://www.careercup.com/question?id=139667&form=comments
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include<string.h>
#define STDOUT 1
#define MAX_INT_LEN 10
//function foo taken from manpages of stdarg
void Printf(char *fmt, ...)
{
va_list ap;
int d;
char c, *s;
va_start(ap, fmt);
while (*fmt)
switch (*fmt++) {
case 's': /* string */
s = va_arg(ap, char *);
write(STDOUT, s, strlen(s));
break;
case 'd': /* int */
d = va_arg(ap, int);
s = malloc(MAX_INT_LEN);
sprintf(s, "%d", d); // lame attempt to convert int to string, no itoa() in linux
write(STDOUT, s, strlen(s));
free(s);
break;
case 'c': /* char */
/* need a cast here since va_arg only
takes fully promoted types */
c = (char) va_arg(ap, int);
write(STDOUT, &c, 1);
break;
}
va_end(ap);
}
int main() {
Printf("%s %d %c", "hello world", 123456 , 's');
}