aboutsummaryrefslogtreecommitdiffstats
path: root/timer.c
blob: 5ab51c67f48886b073f042634407b1a1df04b5cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

unsigned long long int get_seconds(char *);

void usage(char *cmd)
{
    printf("Usage:\n"
           "    %s <n>{s,m,h,D,M,Y} ...\n", cmd);
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("Not enough arguments.\n");
        usage(argv[0]);
        exit(1);
    }

    unsigned long long int total_seconds = 0;

    int i;
    for (i = 1; i < argc; i++)
        total_seconds += get_seconds(argv[i]);

    printf("Total time: %llu second(s).\n", total_seconds);

    return 0;
}

unsigned long long int get_seconds(char *code)
{
    int length = strlen(code);
    if (length < 2) {
        return 0;
    }

    int multiplier = 0;
    char suffix = code[length - 1];
    switch (suffix) {
        case 's': multiplier = 1; break; // 1 second
        case 'm': multiplier = 60; break; // 1 minute
        case 'h': multiplier = 3600; break; // 1 hour
        case 'D': multiplier = 86400; break; // 1 day
        case 'M': multiplier = 2419200; break; // 28 days
        case 'Y': multiplier = 31536000; break; // 365 days
        default : return 0;
    }

    char value[length + 1];
    strcpy(value, code);

    value[length - 1] = '\0';

    return strtoull(value, NULL, 10) * multiplier;
}