Информация об изменениях

Сообщение Re: Разное поведение vs(n)printf в Win и Lin от 29.10.2014 11:21

Изменено 29.10.2014 11:21 niXman

Здравствуйте, Tujh, Вы писали:

T> length = vsnprintf( 0, 0, format, args );

никогда не видел такого...

вот что говорит man:

To allocate a sufficiently large string and print into it (code correct for both glibc 2.0 and glibc 2.1):
(If truncation occurs in glibc versions prior to 2.0.6, this is treated as an error instead of being handled gracefully)

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

char *
make_message(const char *fmt, ...)
{
int n;
int size = 100; /* Guess we need no more than 100 bytes */
char *p, *np;
va_list ap;

if ((p = malloc(size)) == NULL)
return NULL;

while (1) {

/* Try to print in the allocated space */

va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);

/* Check error code */

if (n < 0)
return NULL;

/* If that worked, return the string */

if (n < size)
return p;

/* Else try again with more space */

size = n + 1; /* Precisely what is needed */

if ((np = realloc (p, size)) == NULL) {
free(p);
return NULL;
} else {
p = np;
}
}
}

Здравствуйте, Tujh, Вы писали:

T> length = vsnprintf( 0, 0, format, args );

никогда не видел такого...

вот что говорит man:
       To allocate a sufficiently large string and print into it (code correct for both glibc 2.0 and glibc 2.1):
       (If truncation occurs in glibc versions prior to 2.0.6, this is treated as an error instead of being handled gracefully)

       #include <stdio.h>
       #include <stdlib.h>
       #include <stdarg.h>

       char *
       make_message(const char *fmt, ...)
       {
           int n;
           int size = 100;     /* Guess we need no more than 100 bytes */
           char *p, *np;
           va_list ap;

           if ((p = malloc(size)) == NULL)
               return NULL;

           while (1) {

               /* Try to print in the allocated space */

               va_start(ap, fmt);
               n = vsnprintf(p, size, fmt, ap);
               va_end(ap);

               /* Check error code */

               if (n < 0)
                   return NULL;

               /* If that worked, return the string */

               if (n < size)
                   return p;

               /* Else try again with more space */

               size = n + 1;       /* Precisely what is needed */

               if ((np = realloc (p, size)) == NULL) {
                   free(p);
                   return NULL;
               } else {
                   p = np;
               }
           }
       }