vasprintf (and asprintf)


[Home] Home > Programming > Portability >
vasprintf
#include <stdarg.h>

#include <sys/types.h>

#include <objc/objc.h>
#include <streams/streams.h>

int
vasprintf(char **buf, const char *fmt, va_list args)
{
  NXStream *stream = NULL;
  int       length = 0;

  stream = NXOpenMemory(NULL, 0, NX_READWRITE);
  NXVPrintf(stream, fmt, args);
  NXFlush(stream);

  NXSeek(stream, 0, NX_FROMEND);
  length = NXTell(stream);

  if (length == 0) {
    return 0;
  }

  NXSeek(stream, 0, NX_FROMSTART);
  /* Prefer xmalloc over NX_MALLOC due to error handling. */
  *buf = xmalloc((length + 1) * sizeof(char));

  NXRead(stream, *buf, length);
  NXCloseMemory(stream, NX_FREEBUFFER);
  buf[length] = '\0';

  return length;
}

Which of course allows a trivial asprintf:

int
asprintf(char **strp, const char *fmt, ...)
{
  va_list ap;
  size_t  res = 0;

  va_start(ap, fmt);
  res = vasprintf(strp, fmt, ap);
  va_end(ap);

  return res;
}

Copyright © 2010-2024 Paul Ward.
License Information