質問

Sprintf()が必要とするスペースを予測するために使用できる場所の周りに機能がありますか? IOW、sprintf( "%s n"、some_string)から生じるc-stringの長さを返す関数size_t predict_space( "%s n"、some_string)を呼び出すことはできますか?

役に立ちましたか?

解決

C99 snprintf (注:WindowsとSUSV2は、標準に準拠しているSNPRINTF(または_SNPRINTF)の実装を提供しません):

       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.

例えば:

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);
    }
}

他のヒント

使用するには、0のサイズのsnprintf()を使用して、必要なバイトの数を正確に確認できます。価格は、文字列が効果が2回フォーマットされていることです。

使用できます snprintf そのために、そのように

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

しかし、Autoconfを参照してください 移植性メモ の上 snprintf.

ほとんどの場合、使用した形式に基づいて、連結している文字列の長さを追加し、数値の最大値を取得することで計算できます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top