Vorhersage von Len einer Sprintf () 'ed Line?
-
26-10-2019 - |
Frage
Gibt es irgendwo eine Funktion, mit der ich den Raum, den Sprintf () benötigen wird, vorhergesagt werden kann? Iow, kann ich eine Funktion size_t predict_space ("%s n", son_string) aufrufen, die die Länge der C-String zurückgibt, die sich aus Sprintf ("%s n", sonstring) ergibt?
Lösung
Im C99 snprintf
(Hinweis: Windows und SUSV2 bieten keine Implementierung von SNPRINTF (oder _SNPRINTF) an, die dem Standard entspricht):
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.
Zum Beispiel:
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);
}
}
Andere Tipps
Verwendung kann SNPrintf () mit einer Größe von 0 verwenden, um genau herauszufinden, wie viele Bytes erforderlich sind. Der Preis ist, dass die Zeichenfolge zweimal formatiert ist.
Sie können verwenden snprintf
dafür wie in
sz = snprintf (NULL, 0, fmt, arg0, arg1, ...);
Aber siehe Autoconfs Portabilitätsnotizen an snprintf
.
In den meisten Fällen können Sie es berechnen, indem Sie die Länge der von Ihnen verketteten Zeichenfolge hinzufügen und die maximale Länge für numerische Werte basierend auf dem von Ihnen verwendeten Format einnehmen.