Last active
December 14, 2017 22:02
-
-
Save taeber/20d6b000ae68f5f623f3467233017f34 to your computer and use it in GitHub Desktop.
Simple Countdown Timer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Copyright 2017 Taeber Rapczak | |
* | |
* Simple countdown timer | |
* | |
* EXAMPLES | |
* $ timer 10 # sets timer for 10 seconds | |
* $ timer 1m # sets timer for 1 minute | |
* $ timer 3h5m2 # sets timer for 3 hours, 5 minutes, 2 seconds | |
*/ | |
#include <ctype.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
unsigned parse(char text[]) | |
{ | |
unsigned | |
hours = 0, | |
minutes = 0, | |
seconds = 0; | |
char current; | |
for (unsigned i = 0; (current = text[i]) != '\0'; i++) { | |
if (current == 'h') { | |
hours = seconds; | |
minutes = seconds = 0; | |
} else if (current == 'm') { | |
minutes = seconds; | |
seconds = 0; | |
} else if (isdigit(current)) { | |
seconds = (seconds*10) + (current-'0'); /* ASCII math */ | |
} | |
} | |
return hours*3600 + minutes*60 + seconds; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
unsigned remaining; /* seconds remaining */ | |
remaining = argc == 2? parse(argv[1]): 0; | |
printf("Timer: %d seconds\n", remaining); | |
for (; remaining > 0; remaining--) { | |
printf("\r%02d:%02d:%02d", | |
remaining/3600, /* hours */ | |
(remaining%3600)/60, /* minutes */ | |
remaining%60 /* seconds */ | |
); | |
fflush(stdout); | |
sleep(1); | |
} | |
printf("\r00:00:00\a\n"); /* ring the bell! */ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment