bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Bug-gnulib] Re: snprintf


From: Bruno Haible
Subject: Re: [Bug-gnulib] Re: snprintf
Date: Fri, 1 Oct 2004 18:12:35 +0200
User-agent: KMail/1.5

Simon Josefsson wrote:
> I don't understand, could you be more specific?  snprintf still need
> to return the full length, so it has to be computed somehow.

What I meant is this. Does this look OK?

Bruno


/* Print formatted output to string STR.  Similar to sprintf, but
   additional length SIZE limit how much is written into STR.  Returns
   string length of formatted string (which may be larger than SIZE).
   STR may be NULL, in which case nothing will be written.  On error,
   return a negative value. */
int
snprintf (char *str, size_t size, const char *format, ...)
{
  char *output;
  size_t len;
  va_list args;

  va_start (args, format);
  len = size;
  output = vasnprintf (str, &len, format, args);
  va_end (args);

  if (!output)
    return -1;

  if (str != NULL)
    if (len > size - 1) /* equivalent to: (size > 0 && len >= size) */
      str[size - 1] = '\0';

  if (output != str)
    free (output);

  return len;
}





reply via email to

[Prev in Thread] Current Thread [Next in Thread]