[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Sun, 24 Jan 2010 20:51:58 +0100
Robert Millan wrote:
> I implemented xctime for GNU isofsmk. xctime is an alternative to ctime()
> - Uses dynamic allocation
> - Is thread-safe
> - Returns localized strings
I agree that it's not a good idea to use ctime() or asctime(), because of
the problems mentioned in gnulib/doc/posix-functions/*ctime.texi.
> char *
> xctime (const time_t *time)
> struct tm *loctime;
> char *str;
> size_t len;
> loctime = localtime (time);
> len = strftime (NULL, INT32_MAX, "%c", loctime) + sizeof ("");
> str = xmalloc (len);
> strftime (str, len, "%c", loctime);
> return str;
> I find it much more comfortable than having to deal with strftime() every
> time. If you're interested, I could make a Gnulib module out of it.
Hmm, if this is proposed for gnulib, I have 4 remarks:
- Error handling: strftime can fail. Since you call xmalloc for the
memory allocation, I think it would be reasonable to call error()
in case strftime fails.
- Flexibility: The three most often used formats are probably %c, %x, %X.
Any function for date formatting should not have the format built-in.
It should have a format indication as argument. But then you can also
allow the user to pass an entire format string. And define shorthands
as reminders like this:
#define TIMEFORMAT_LOCALE_DATETIME "%c"
#define TIMEFORMAT_LOCALE_DATE "%x"
#define TIMEFORMAT_LOCALE_TIME "%X"
- In the average case, you can get away with 1 strftime call instead of 2,
if you preallocate a buffer on the stack:
len = strftime (buf, sizeof (buf), "%c", loctime) + 1;
In the case where 256 bytes are not enough, the function will need
3 strftime calls instead of 1, but this case should be pretty rare
(even in Chinese and GB18030 encoding, 64 characters should be enough
for a date + time display).
- sizeof ("") is confusing. You can write 1 instead.
- xctime(), Robert Millan, 2010/01/24
- Re: xctime(),
Bruno Haible <=