You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

asprintf.c 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <stdint.h>
  2. #include <stddef.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <errno.h>
  6. FILE_LICENCE ( GPL2_OR_LATER );
  7. /**
  8. * Write a formatted string to newly allocated memory.
  9. *
  10. * @v strp Pointer to hold allocated string
  11. * @v fmt Format string
  12. * @v args Arguments corresponding to the format string
  13. * @ret len Length of formatted string
  14. */
  15. int vasprintf ( char **strp, const char *fmt, va_list args ) {
  16. size_t len;
  17. va_list args_tmp;
  18. /* Calculate length needed for string */
  19. va_copy ( args_tmp, args );
  20. len = ( vsnprintf ( NULL, 0, fmt, args_tmp ) + 1 );
  21. va_end ( args_tmp );
  22. /* Allocate and fill string */
  23. *strp = malloc ( len );
  24. if ( ! *strp )
  25. return -ENOMEM;
  26. return vsnprintf ( *strp, len, fmt, args );
  27. }
  28. /**
  29. * Write a formatted string to newly allocated memory.
  30. *
  31. * @v strp Pointer to hold allocated string
  32. * @v fmt Format string
  33. * @v ... Arguments corresponding to the format string
  34. * @ret len Length of formatted string
  35. */
  36. int asprintf ( char **strp, const char *fmt, ... ) {
  37. va_list args;
  38. int len;
  39. va_start ( args, fmt );
  40. len = vasprintf ( strp, fmt, args );
  41. va_end ( args );
  42. return len;
  43. }