1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2024-11-09 21:32:02 +05:30

add c-programming/asprintf.*

This commit is contained in:
Intel A80486DX2-66 2024-01-15 19:42:17 +03:00
parent 1085b5df6e
commit 5464b1f85a
Signed by: 80486DX2-66
GPG Key ID: 83631EF27054609B
2 changed files with 38 additions and 0 deletions

28
c-programming/asprintf.c Normal file
View File

@ -0,0 +1,28 @@
#include "asprintf.h"
ssize_t asprintf(char** strp, char* format, ...) {
va_list args;
va_start(args, format);
ssize_t size = (ssize_t) vsnprintf(NULL, 0, format, args);
if (size < 0) {
va_end(args);
return -1;
}
*strp = malloc(size + 1);
if (*strp == NULL) {
va_end(args);
return -1;
}
ssize_t result = (ssize_t) vsnprintf(*strp, size + 1, format, args);
va_end(args);
if (result < 0) {
free(*strp);
return -1;
}
return result;
}

10
c-programming/asprintf.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef _ASPRINTF_H
#define _ASPRINTF_H
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
ssize_t asprintf(char** strp, char* format, ...);
#endif /* _ASPRINTF_H */