Re: snprint rationale?
In <cnsamm0eu8@new s2.newsguy.com> Chris Torek <nospam@torek.n et> writes:
[color=blue]
>In article <pan.2004.11.22 .03.43.11.23569 5.512@ioplex.co m>
>Michael B Allen <mba2000@ioplex .com> wrote:[color=green]
>>What is the rationale for snprintf to "return the number of characters
>>(excluding the trailing '\0') which would have been written to the final
>>string if enough space had been available"?[/color]
>
>This lets you allocate a buffer that is big enough, without having
>to do many passes:
>
> needed = snprintf(NULL, 0, fmt, arg1, arg2);
> if (needed < 0) ... handle error ...
> mem = malloc(needed + 1);
> if (mem == NULL) ... handle error ...
> result = snprintf(mem, needed + 1, fmt, arg1, arg2);[/color]
No point in calling snprintf again, sprintf would do just fine:
result = sprintf(mem, fmt, arg1, arg2);
And, unless you're really paranoid, you don't even need its return value,
because it *must* be equal to ``needed'' (if the original snprintf call
succeeded, a sprintf call with the same arguments and in the same locale
must return the same value).
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Dan.Pop@ifh.de
Currently looking for a job in the European Union
In <cnsamm0eu8@new s2.newsguy.com> Chris Torek <nospam@torek.n et> writes:
[color=blue]
>In article <pan.2004.11.22 .03.43.11.23569 5.512@ioplex.co m>
>Michael B Allen <mba2000@ioplex .com> wrote:[color=green]
>>What is the rationale for snprintf to "return the number of characters
>>(excluding the trailing '\0') which would have been written to the final
>>string if enough space had been available"?[/color]
>
>This lets you allocate a buffer that is big enough, without having
>to do many passes:
>
> needed = snprintf(NULL, 0, fmt, arg1, arg2);
> if (needed < 0) ... handle error ...
> mem = malloc(needed + 1);
> if (mem == NULL) ... handle error ...
> result = snprintf(mem, needed + 1, fmt, arg1, arg2);[/color]
No point in calling snprintf again, sprintf would do just fine:
result = sprintf(mem, fmt, arg1, arg2);
And, unless you're really paranoid, you don't even need its return value,
because it *must* be equal to ``needed'' (if the original snprintf call
succeeded, a sprintf call with the same arguments and in the same locale
must return the same value).
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Dan.Pop@ifh.de
Currently looking for a job in the European Union
Comment