From 48e46e8698545ef61b57a7e5dacd10a167820d9b Mon Sep 17 00:00:00 2001 From: Sami Kerola Date: Fri, 4 Jan 2019 22:18:53 +0000 Subject: [PATCH] other: use strftime() to generate date-time string It is better to use library function to create date-time string than sprintf various struct tm members. In same go retire time() call that is obsoleted by clock_gettime(). Signed-off-by: Sami Kerola --- src/other.c | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/src/other.c b/src/other.c index 63d094b..50f2380 100644 --- a/src/other.c +++ b/src/other.c @@ -551,31 +551,23 @@ void clean_up(struct conf_t *state) } /*! \brief Print a time stamp of a path or now to output file. */ -void dp_time_tool(FILE *file, const char *path, int epoch) +void dp_time_tool(FILE *file, const char *path, const int epoch) { - time_t t; - - /* a file or now */ - if (path) { - struct stat st; + struct stat st; + if (path) stat(path, &st); - t = st.st_mtime; - } else - t = time(NULL); - /* epoc or iso time stamp */ + else + clock_gettime(CLOCK_REALTIME, &st.st_mtim); if (epoch) - fprintf(file, "%ld", t); + fprintf(file, "%ld", st.st_mtim.tv_sec); else { char time_stamp[64]; + const time_t mtime = st.st_mtim.tv_sec; struct tm tm; - int len; - localtime_r(&t, &tm); - len = snprintf(time_stamp, sizeof(time_stamp), "%4d-%.2d-%.2dT%02d:%02d:%02d", - tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec); - strftime(time_stamp + len, sizeof(time_stamp) - len, "%z", &tm); + localtime_r(&mtime, &tm); + strftime(time_stamp, sizeof(time_stamp), "%FT%T%z", &tm); fprintf(file, "%s", time_stamp); } }