I
Ike Naar
Barry Schwarz said:snprintf will return the number of characters that would have been
written if n had been large enough. %24s provides a minimum width.
Adding 1 for the '\n' and 1 for the '\0' means showtime will always
return at least 26.
What is the the purpose of defining a minimum width of field in a format
specifier, if 'snprintf' will write different number of chars?
Considering all the amendments, I fix the code as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define BUFSIZE(b) (sizeof b)
static size_t
showtime(char buf[], const size_t len)
{
time_t ticks;
int nchars;
if ( (ticks = time(NULL)) < 0 ) {
ticks = 0;
}
nchars = snprintf(buf, len, "%25s", ctime(&ticks));
return nchars;
}
int main(void)
{
char buf[26] = "";
size_t n;
n = showtime(buf, sizeof buf);
if ( n >= 0 && n < BUFSIZE(buf)) {
ctime returns the address of a string of length 25. snprintf will add
a '\0' to this. showtime should always return 26. The right operand
of the && operator should always evaluate to false.
snprintf returns the number of characters that would have been
printed if the size of the buffer were unlimited, *excluding* the
final '\0'.
So if the string returned by ctime has length 25,
then snprintf, and hence showtime, return 25 as well.
Style issues:
What's the added value of the BUFSIZE macro?
Why is ``sizeof buf'' used in the showtime call, but ``BUFSIZE(buf)''
in the ``if'' expression that follows it?
n is an unsigned number, so the ``n >= 0'' test always returns true.