Skip to content

Instantly share code, notes, and snippets.

@bynux-gh
Last active July 6, 2024 00:31
Show Gist options
  • Save bynux-gh/78423d86ef9684fc492948e67724c62f to your computer and use it in GitHub Desktop.
Save bynux-gh/78423d86ef9684fc492948e67724c62f to your computer and use it in GitHub Desktop.
A basic timer application. Can be used alongside other terminal commands to give them a required countdown before executing.
/* CTimer - A dead-simple console timer by Bryn Miller.
*
* Recommended use case: `ctimer $TIME && other-command`
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char** argv) {
int m; int s;
char values[10];
// Get value from argument or prompt.
if (argc > 1) {
if (strlen(argv[1]) > 10) {
fprintf(stderr, "Maximum value is 999999:59\n");
return 65; // EX_DATAERR
}
strcpy(values, argv[1]);
} else {
printf("For how long? (mm:ss) > ");
fgets(values, sizeof values, stdin);
}
// Check that the input is valid...
// Empty string.
if (values[1] == '\0') {
fprintf(stderr, "You have to put a time in.\n");
return 66; // EX_NOINPUT
}
// If not empty or just a newline, try to pull integers
if (sscanf(values, "%u:%u", &m, &s) != 2) { // Error if both ints aren't assigned
fprintf(stderr, "Invalid input; use \"mm:ss\" format (e.g. 4:20 for 4 minutes and 20 seconds).\n");
return 64; // EX_USAGE
}
// No negative values accepted.
if (s < 0 || m < 0) {
fprintf(stderr, "Time cannot be less than 0.\n");
return 65; // EX_DATAERR
}
// Cannot have more than 60 seconds in a minute.
if (s > 60) {
fprintf(stderr, "There are no more than 60 seconds in a minute.\n");
return 65; // EX_DATAERR
}
// All checks passed, proceed to countdown.
int totalSecs = m * 60 + s;
setvbuf(stdout, NULL, _IONBF, 32); // Make sure time will display without newline char
for (int i = totalSecs; i > 0; i--) {
printf("\r% 2d:%02d ", i / 60, i % 60); // Follower space erases when number of digits changes.
sleep(1);
}
printf("\r***TIMER DONE***\n\n");
return 0; // EX_OK
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment