myprintf.c
changeset 58 9609c54a54d3
child 60 47c13ca8c4d0
equal deleted inserted replaced
57:7739518acafb 58:9609c54a54d3
       
     1 /**
       
     2  * test/demos/myprintf.c
       
     3  * Copyright (C) 2008 Markus Broeker
       
     4  */
       
     5 
       
     6 #include <stdio.h>
       
     7 #include <stdlib.h>
       
     8 #include <stdarg.h>
       
     9 #include <string.h>
       
    10 
       
    11 int myprintf (char *fmt, ...)
       
    12 {
       
    13     int i, pos = 0;
       
    14     va_list list;
       
    15 
       
    16     char c;
       
    17     char *s;
       
    18     char s_str[1024];
       
    19 
       
    20     char v[12];
       
    21     int value;
       
    22 
       
    23     va_start (list, fmt);
       
    24 
       
    25     while (*fmt) {
       
    26         switch (*fmt) {
       
    27         case '%':
       
    28             switch (*++fmt) {
       
    29             case 'c':
       
    30                 c = va_arg (list, int);
       
    31                 s_str[pos++] = c;
       
    32                 c = *fmt++;
       
    33                 break;
       
    34             case 's':
       
    35                 s = va_arg (list, char *);
       
    36                 for (i = 0; i < strlen (s); i++) {
       
    37                     s_str[pos++] = s[i];
       
    38                 }
       
    39                 c = *fmt++;
       
    40                 break;
       
    41             case 'd':
       
    42                 value = va_arg (list, int);
       
    43                 sprintf (v, "%d", value);
       
    44                 for (i = 0; i < strlen (v); i++) {
       
    45                     s_str[pos++] = v[i];
       
    46                 }
       
    47                 c = *fmt++;
       
    48                 break;
       
    49             default:
       
    50                 puts ("Unknown character");
       
    51             }
       
    52         default:
       
    53             s_str[pos++] = *fmt++;
       
    54         }
       
    55         va_end (list);
       
    56     }
       
    57 
       
    58     s_str[pos] = '\0';
       
    59 
       
    60     puts (s_str);
       
    61     return pos;
       
    62 }
       
    63 
       
    64 int main (int argc, char **argv)
       
    65 {
       
    66     int len;
       
    67 
       
    68     len = myprintf ("Bugfix needed: %s\t[%d:%d]", "Lines", 20, 30);
       
    69     return EXIT_SUCCESS;
       
    70 }