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:
parent
1085b5df6e
commit
5464b1f85a
28
c-programming/asprintf.c
Normal file
28
c-programming/asprintf.c
Normal 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
10
c-programming/asprintf.h
Normal 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 */
|
Loading…
Reference in New Issue
Block a user