2011-03-17 1 views
2

sprintf()가 필요로하는 공간을 예측하는 데 사용할 수있는 함수가 있습니까? IOW, sprintf ("% s \ n", some_string)에서 발생하는 C 문자열의 길이를 반환하는 size_t predict_space ("% s \ n", some_string) 함수를 호출 할 수 있습니까?sprintf()의 행을 예측 했습니까?

+0

왜'some_string'에'strlen'을 사용하고 그 공간을 사용하여 필요한 공간을 계산해야하지 않습니까? – MAK

+2

@MAK 아마도 OP는 다른 형식 지정자 및 여러 매개 변수로 작동하는 일반적인 솔루션을 원합니다. –

+2

답변에 따르면,'snprintf'는 아마 갈 길입니다. 그 함수가없는 시스템에서 우리는'FILE * fh = fopen ("/ dev/null", "w")'그리고'x = fprintf (fh, fmtstr, blah, blah, blah);를 사용했다. 길이. – paxdiablo

답변

9

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); 
    } 
} 
: 예를 들어

 
     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. 

+0

snountf의 반환 값과 관련하여 SUSv2와 C99 스탠드가 서로 모순됩니다. snprintf가 size = 0으로 호출 될 때 SUSv2는 1보다 작은 지정되지 않은 반환 값을 규정하고 C99 은 이 경우 NULL이되도록 str을 지정하고 출력 문자열이 충분히 큰 경우 경우에 쓰여진 문자 수로 반환 값 (항상 )을 제공합니다. –

+0

@Benoit, 아마도'char x; int len ​​= snprintf (& x, 1, fmtstr, blah, blah, blah);이 경우. – paxdiablo

6

크기가 0 인 snprintf()를 사용하면 정확히 필요한 바이트 수를 알 수 있습니다. 가격은 문자열이 실제로 두 번 서식이 지정된다는 것입니다. (: 표준에 부합하는 Windows 및 SUSv2, 현재 snprintf (또는 _snprintf의 구현을 제공하지 않는) 주) : C99snprintf에서

+0

주의하십시오. 맨 페이지 추출 : snprintf() 함수는 문자 수를 으로 반환합니다. 즉, 충분히 큰 경우 이 버퍼에 쓰여질 문자 수를 반환합니다. snprintf()에 대한 호출에서 의 n 값이 0이면 지정되지 않은 값이 1보다 작습니다. –

+2

@Benoit : 이것은 표준이 묘사하는 행동이 아닙니다. – pmg

+1

snprintf의 반환 값과 관련하여 SUSv2와 C99 스탠드가 서로 모순됩니다. snprintf가 size = 0과 함께 호출 될 때 SUSv2는 지정되지 않은 반환 값을 1 미만으로 규정하고 C99 은 str을 NULL로 허용합니다. 이 경우 출력 문자열이 충분히 큰 경우 경우에 쓰여진 문자 수로 반환 값 (항상 으로)을 제공합니다. 그러나 –

2

와 같이 snprintf을 사용할 수 있습니다.

그러나 Autoconf의 portability notes (snprintf)을 참조하십시오.

+0

경고 : snprintf의 반환 값에 관해서는 SUSv2와 C99 스탠드가 서로 모순됩니다. snprintf가 size = 0과 함께 호출 될 때 SUSv2는 지정되지 않은 반환 값을 1보다 작게 지정하고 C99 은 str을 허용합니다 이 경우 NULL이며, 출력 문자열이 충분히 큰 경우 경우에 쓰여진 문자 수로 반환 값 (항상 )을 제공합니다. –

2

대부분의 경우 연결하려는 문자열의 길이를 더하고 사용한 형식에 따라 숫자 값의 최대 길이를 취하여 계산할 수 있습니다.