iPXE
asprintf.c
Go to the documentation of this file.
00001 #include <stdint.h>
00002 #include <stddef.h>
00003 #include <stdlib.h>
00004 #include <stdio.h>
00005 #include <errno.h>
00006 
00007 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
00008 
00009 /**
00010  * Write a formatted string to newly allocated memory.
00011  *
00012  * @v strp              Pointer to hold allocated string
00013  * @v fmt               Format string
00014  * @v args              Arguments corresponding to the format string
00015  * @ret len             Length of formatted string
00016  */
00017 int vasprintf ( char **strp, const char *fmt, va_list args ) {
00018         size_t len;
00019         va_list args_tmp;
00020 
00021         /* Calculate length needed for string */
00022         va_copy ( args_tmp, args );
00023         len = ( vsnprintf ( NULL, 0, fmt, args_tmp ) + 1 );
00024         va_end ( args_tmp );
00025 
00026         /* Allocate and fill string */
00027         *strp = malloc ( len );
00028         if ( ! *strp )
00029                 return -ENOMEM;
00030         return vsnprintf ( *strp, len, fmt, args );
00031 }
00032 
00033 /**
00034  * Write a formatted string to newly allocated memory.
00035  *
00036  * @v strp              Pointer to hold allocated string
00037  * @v fmt               Format string
00038  * @v ...               Arguments corresponding to the format string
00039  * @ret len             Length of formatted string
00040  */
00041 int asprintf ( char **strp, const char *fmt, ... ) {
00042         va_list args;
00043         int len;
00044 
00045         va_start ( args, fmt );
00046         len = vasprintf ( strp, fmt, args );
00047         va_end ( args );
00048         return len;
00049 }