Domanda

C'è una funzione da qualche parte che posso usare per prevedere lo spazio che sprintf () avrà bisogno? IOW, posso chiamare una funzione di predict_space size_t ( "% s \ n", some_string) che restituirà la lunghezza della C-stringa che sarà il risultato di sprintf ( "% s \ n", some_string)?

È stato utile?

Soluzione

Nel C99 snprintf (nota: Windows e SUSv2, non forniscono un'implementazione di snprintf (o _snprintf) conforme allo standard) :

       7.19.6.5  The snprintf function

       Synopsis

       [#1]

               #include <stdio.h>
               int snprintf(char * restrict s, size_t n,
                       const char * restrict format, ...);

       Description

       [#2]  The snprintf function is equivalent to fprintf, except
       that the output is  written  into  an  array  (specified  by
       argument  s) rather than to a stream.  If n is zero, nothing
       is written, and s may be a null pointer.  Otherwise,  output
       characters  beyond the n-1st are discarded rather than being
       written to the array, and a null character is written at the
       end  of  the characters actually written into the array.  If
       copying  takes  place  between  objects  that  overlap,  the
       behavior is undefined.

       Returns

       [#3]  The snprintf function returns the number of characters
       that would have been written had n been sufficiently  large,
       not  counting  the terminating null character, or a negative
       value if  an  encoding  error  occurred.   Thus,  the  null-
       terminated output has been completely written if and only if
       the returned value is nonnegative and less than n.

Ad esempio:

len = snprintf(NULL, 0, "%s\n", some_string);
if (len > 0) {
    newstring = malloc(len + 1);
    if (newstring) {
        snprintf(newstring, len + 1, "%s\n", some_string);
    }
}

Altri suggerimenti

L'uso può utilizzare snprintf () con una dimensione di 0 a scoprire esattamente quanti byte sarà richiesto. Il prezzo è che la stringa è in effetti formattato due volte.

È possibile utilizzare snprintf per questo, come in

sz = snprintf (NULL, 0, fmt, arg0, arg1, ...);

Ma vedi portabilità note di Autoconf su snprintf.

Nella maggior parte dei casi, si può calcolare che con l'aggiunta di lunghezza della stringa che si sta concatenato e prendendo lunghezza massima per i valori numerici in base al formato che hai utilizzato.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top