os-k/kaleid/crtlib/sprintf.c

91 lines
3.0 KiB
C
Raw Normal View History

2019-01-21 15:00:04 +01:00
//----------------------------------------------------------------------------//
// GNU GPL OS/K //
// //
2019-02-16 23:36:33 +01:00
// Desc: *s*printf() family //
2019-01-21 15:00:04 +01:00
// //
2019-02-16 23:36:33 +01:00
// //
// Copyright © 2018-2019 The OS/K Team //
// //
// This file is part of OS/K. //
// //
// OS/K is free software: you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation, either version 3 of the License, or //
// any later version. //
// //
// OS/K is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY//without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with OS/K. If not, see <https://www.gnu.org/licenses/>. //
2019-01-21 15:00:04 +01:00
//----------------------------------------------------------------------------//
#include <kalbase.h>
//
// Format str according to fmt using ellipsed arguments
//
// BE CAREFUL when using this
// you need to know for sure an overflow won't happen
//
int sprintf(char *str, const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap);
ret = vsnprintf(str, SIZE_T_MAX, fmt, ap);
va_end(ap);
return ret;
}
int vsprintf(char *str, const char *fmt, va_list ap)
{
return vsnprintf(str, SIZE_T_MAX, fmt, ap);
}
//
// (v)sprintf() but with a size limit: no more than n bytes are written in str
// Always null-terminate str
//
int snprintf(char *str, size_t n, const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap);
ret = vsnprintf(str, n, fmt, ap)
va_end(ap);
return ret;
}
int vsnprintf(char *str, size_t n, const char *fmt, va_list ap)
{
int ret = 0;
// Go throught the format string
while (*fmt) {
if (*fmt != '%') {
// Even if we don't have any more room we still increase ret
if (ret++ < n) {
*str++ = *fmt++;
}
continue;
}
switch (*fmt) {
case 'd':
default:
break;
}
}
return ret;
}