Friday, December 9, 2011

time delay routine in C

/*
 * filename : counter.c
 * date     : 09-12-2011
 */

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

char default_msg[] = "counter will expire in following seconds";

int main(int argc, char* argv[])
{
    char *msg = default_msg;
    int delay = 0, hour, min, sec, days;
    int i;

    days = hour = min = sec = 0;

    switch (argc)
    {
        case 3:
            msg = argv[2];
        case 2:

            for (i=0; i < strlen(argv[1]); i++)
            {
                if (!isdigit(argv[1][i]))
                {
                    printf("invalid digit '%c' at position %d in argument\n", argv[1][i], i);
                    return -1;
                }
            }
            delay = atoi(argv[1]);
            break;
        default:
            printf("invalid number of arguments\n"
                    "usage: %s [\"message\"]\n", argv[0]);
            fflush(stdout);
            return -1;
    }

    /*
     * calculate exact time in hh:mm:ss entered for delay-sec
     */
    sec  = delay % 60;
    min  = (delay / 60) % 60;
    hour = (delay / 3600) % 24;
    days = delay / (3600 * 24);

    printf("MSG: %s - DAYS: %d, %d:%d:%d\n", msg, days, hour, min, sec);
    for (i=delay; i >= 0 ; i--)
    {
        printf("\rcounter: %d", i);
        fflush(stdout);        sleep(1);
    }
    printf("\n");

    return 0;
}


/*
* compile with gcc
* gcc counter.c -o COUNTER
* ./COUNTER 15
* ./COUNTER 97405
*/