Bipins Dot Net daily bits and pieces

8Jul/090

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');
}

Filed under: old Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.

6 visitors online now
6 guests, 0 members
All time: 15 at 07-27-2010 07:36 am UTC
Max visitors today: 6 at 12:58 pm UTC
This month: 6 at 09-07-2010 12:58 pm UTC
This year: 15 at 07-27-2010 07:36 am UTC