選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

asprintf.c 1.1KB

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