diff options
author | Marvin Borner | 2020-05-28 21:17:21 +0200 |
---|---|---|
committer | Marvin Borner | 2020-05-28 21:17:21 +0200 |
commit | 731ea56513bd199597a905eb1937e67cbd762b32 (patch) | |
tree | 053f4bdb548ee9d5833c4ede0498e39a7aa68787 /src | |
parent | f676cc7bb821f498efe73f38bf19b43e4b91f575 (diff) |
Added sprintf function
Diffstat (limited to 'src')
-rw-r--r-- | src/kernel/lib/stdio.h | 2 | ||||
-rw-r--r-- | src/kernel/lib/stdio/sprintf.c | 63 |
2 files changed, 65 insertions, 0 deletions
diff --git a/src/kernel/lib/stdio.h b/src/kernel/lib/stdio.h index 26b9ce8..dff4044 100644 --- a/src/kernel/lib/stdio.h +++ b/src/kernel/lib/stdio.h @@ -5,6 +5,8 @@ void putch(char c); +int sprintf(char *str, const char *fmt, ...); + void vprintf(const char *fmt, va_list args); void printf(const char *fmt, ...); diff --git a/src/kernel/lib/stdio/sprintf.c b/src/kernel/lib/stdio/sprintf.c new file mode 100644 index 0000000..0fb6eb5 --- /dev/null +++ b/src/kernel/lib/stdio/sprintf.c @@ -0,0 +1,63 @@ +#include <lib/stdlib.h> +#include <stdarg.h> +#include <stdint.h> + +static void append(char *dest, char *src, int index) +{ + for (int i = index; i < strlen(src) + index; i++) + dest[i] = src[i - index]; + dest[index + strlen(src)] = 0; +} + +int sprintf(char *str, const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + + u8 ready_to_format = 0; + + int i = 0; + char buf = 0; + char format_buffer[20] = "\0"; + + for (; *fmt; fmt++) { + if (ready_to_format) { + ready_to_format = 0; + + if (*fmt == '%') { + str[i] = '%'; + continue; + } + + buf = *fmt; + if (buf == 's') { + char *string = va_arg(args, char *); + append(str, string, i); + i = strlen(str); + } else if (buf == 'x') { + itoa_base((u32)va_arg(args, int), format_buffer, 16); + append(str, format_buffer, i); + i = strlen(str); + } else if (buf == 'd') { + itoa_base(va_arg(args, int), format_buffer, 10); + append(str, format_buffer, i); + i = strlen(str); + } else if (buf == 'c') { + str[i] = (char)va_arg(args, int); + i++; + } + } else { + if (*fmt == '%') + ready_to_format = 1; + else { + str[i] = *fmt; + i++; + } + } + + format_buffer[0] = '\0'; + } + + va_end(args); + return strlen(str); +}
\ No newline at end of file |