sprintf.c (627B)
1 2 #include <stdio.h> 3 #include <errno.h> 4 5 #include "ioprivate.h" 6 7 struct sprintbuf { 8 char *buf; 9 }; 10 11 static int 12 sprintputch(int ch, struct sprintbuf *b) 13 { 14 *b->buf++ = ch; 15 return 0; 16 } 17 18 int 19 vsprintf(char *buf, const char *fmt, va_list ap) 20 { 21 struct sprintbuf b = {buf}; 22 23 if (buf == NULL) { 24 errno = EINVAL; 25 return -1; 26 } 27 28 // print the string to the buffer 29 int cnt = vprintfmt((void*)sprintputch, &b, fmt, ap); 30 31 // null terminate the buffer 32 *b.buf = '\0'; 33 34 return cnt; 35 } 36 37 int 38 sprintf(char *buf, const char *fmt, ...) 39 { 40 va_list ap; 41 int rc; 42 43 va_start(ap, fmt); 44 rc = vsprintf(buf, fmt, ap); 45 va_end(ap); 46 47 return rc; 48 } 49