stdio: add asprintf and vasprintf

This commit is contained in:
Lephenixnoir 2021-06-07 19:09:55 +02:00
parent f52e0923bc
commit 625a6af459
No known key found for this signature in database
GPG key ID: 1BBA026E13FC0495
4 changed files with 41 additions and 0 deletions

View file

@ -114,6 +114,7 @@ set(SOURCES
src/libc/signal/signal.c
src/libc/signal/raise.c
# stdio
src/libc/stdio/asprintf.c
src/libc/stdio/dprintf.c
src/libc/stdio/fprintf.c
src/libc/stdio/printf.c
@ -124,6 +125,7 @@ set(SOURCES
src/libc/stdio/puts.c
src/libc/stdio/snprintf.c
src/libc/stdio/sprintf.c
src/libc/stdio/vasprintf.c
src/libc/stdio/vdprintf.c
src/libc/stdio/vfprintf.c
src/libc/stdio/vprintf.c

View file

@ -81,4 +81,11 @@ extern int dprintf(int __fd, char const * restrict __format, ...);
/* Formatted print to file descriptor (variable argument list). */
extern int vdprintf(int __fd, char const * restrict __format, va_list __args);
/* Allocating sprintf(). */
extern int asprintf(char ** restrict __str,char const * restrict __format,...);
/* Allocating vsprintf(). */
extern int vasprintf(char ** restrict __str, char const * restrict __format,
va_list __args);
#endif /*__STDIO_H__*/

13
src/libc/stdio/asprintf.c Normal file
View file

@ -0,0 +1,13 @@
#include <stdio.h>
int asprintf(char **strp, char const *format, ...)
{
va_list args;
va_start(args, format);
int count = vasprintf(strp, format, args);
va_end(args);
return count;
}

View file

@ -0,0 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int vasprintf(char **strp, char const *format, va_list args1)
{
va_list args2;
va_copy(args2, args1);
int count = vsnprintf(NULL, 0, format, args1);
va_end(args1);
char *str = malloc(count + 1);
if(str) count = vsnprintf(str, count + 1, format, args2);
va_end(args2);
if(!str) return -1;
*strp = str;
return count;
}