sts.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Fri, 19 Nov 2010 12:23:24 +0100
changeset 158 2cddd4d26139
parent 156 2898369b1cdc
permissions -rw-r--r--
removed unnecessary #includes committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * sts.c: show time stamp
 * Copyright (C) 2010 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>

void usage (char *name)
{
    printf ("Usage: %s STAMP [BOOT-STAMP]\n", name);
    exit (EXIT_FAILURE);
}

time_t parse (char *buf)
{
    time_t sec = 0;
    time_t milli = 0;

    if (sscanf (buf, "%ld.%ld", &sec, &milli) != 2) {
        fprintf (stderr, "  sec: %ld, ", sec);
        fprintf (stderr, "milli: %ld\n", milli);
    }

    return sec;
}

time_t getboottime ()
{
    char buf[80];
    time_t now = time (NULL);

    FILE *f = fopen ("/proc/uptime", "r");
    if (f == NULL) {
        perror ("FOPEN");
        return EXIT_FAILURE;
    }
    if (fgets (buf, sizeof (buf), f) == NULL) {
        perror ("FOPEN");
        exit (errno);
    }

    fclose (f);
    return now - parse (buf);
}

int main (int argc, char **argv)
{
    time_t boot;
    time_t stamp = 0;
    time_t diff;

    if (argc < 2)
        usage (argv[0]);

    stamp = parse (argv[1]);

    if (argc == 3) {
        boot = parse (argv[2]);
    } else
        boot = getboottime ();

    diff = boot + stamp;
    printf ("%s: %s", argv[1], ctime (&diff));

    return EXIT_SUCCESS;
}