Skip to content
This repository was archived by the owner on Jan 8, 2025. It is now read-only.

Commit

Permalink
[libc] add n versions of sprintf and vprintf
Browse files Browse the repository at this point in the history
  • Loading branch information
travis geiselbrecht authored and travisg committed Dec 31, 2008
1 parent d647d76 commit 9d564f1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
2 changes: 2 additions & 0 deletions include/printf.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ extern "C" {

int printf(const char *fmt, ...);
int sprintf(char *str, const char *fmt, ...) __PRINTFLIKE(2, 3);
int snprintf(char *str, size_t len, const char *fmt, ...) __PRINTFLIKE(3, 4);
int vsprintf(char *str, const char *fmt, va_list ap);
int vsnprintf(char *str, size_t len, const char *fmt, va_list ap);

#if defined(__cplusplus)
}
Expand Down
26 changes: 23 additions & 3 deletions lib/libc/printf.c
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ int sprintf(char *str, const char *fmt, ...)
return err;
}

int snprintf(char *str, size_t len, const char *fmt, ...)
{
int err;

va_list ap;
va_start(ap, fmt);
err = vsnprintf(str, len, fmt, ap);
va_end(ap);

return err;
}


#define LONGFLAG 0x00000001
#define LONGLONGFLAG 0x00000002
Expand Down Expand Up @@ -133,6 +145,11 @@ static char *longlong_to_hexstring(char *buf, unsigned long long u, int len, uin
}

int vsprintf(char *str, const char *fmt, va_list ap)
{
return vsnprintf(str, INT_MAX, fmt, ap);
}

int vsnprintf(char *str, size_t len, const char *fmt, va_list ap)
{
char c;
unsigned char uc;
Expand All @@ -141,10 +158,11 @@ int vsprintf(char *str, const char *fmt, va_list ap)
void *ptr;
int flags;
unsigned int format_num;
int chars_written = 0;
size_t chars_written = 0;
char num_buffer[32];

#define OUTPUT_CHAR(c) do { (*str++ = c); chars_written++; } while(0)
#define OUTPUT_CHAR(c) do { (*str++ = c); chars_written++; if (chars_written + 1 == len) goto done; } while(0)
#define OUTPUT_CHAR_NOLENCHECK(c) do { (*str++ = c); chars_written++; } while(0)

for(;;) {
/* handle regular chars that aren't format related */
Expand Down Expand Up @@ -309,11 +327,13 @@ int vsprintf(char *str, const char *fmt, va_list ap)
continue;
}

done:
/* null terminate */
OUTPUT_CHAR('\0');
OUTPUT_CHAR_NOLENCHECK('\0');
chars_written--; /* don't count the null */

#undef OUTPUT_CHAR
#undef OUTPUT_CHAR_NOLENCHECK

return chars_written;
}
Expand Down

0 comments on commit 9d564f1

Please sign in to comment.