Simple C script to dump an approximate local time

Quick and dirty C function to dump rough/not truly accurate samples for time

/**
 * @file time.c
 * @brief Purpose is to just generate a simple time (not accurate) with milliseconds
 * @note gcc -Wall -o simpletime time.c -lm
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>

#define BUFFER_LEN 100

static void fmt_time(char *output, int len)
{
        time_t r_time;
        struct tm *timeinfo = NULL;

        time(&r_time);
        timeinfo = localtime(&r_time);

        int ms = 0;
        struct timeval tv;

        gettimeofday(&tv, NULL);

        if ((ms = lrint(tv.tv_usec / 1000.0)) >= 1000) {
                ms -= 1000;
                tv.tv_sec++;
        }

        snprintf(output, len, "%d:%d:%d.%03d", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, ms);
}

int main(int argc, char **argv)
{
        char time_str[BUFFER_LEN] = { 0 };

        fmt_time(time_str, BUFFER_LEN);
        printf("time: %s\n", time_str);
        return 0;
}

Output from running the script:

gcc -Wall -o simpletime time.c -lm
 ./simpletime
time: 10:33:58.743

Blog tags: 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <python> <c>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.