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
| #include <stdlib.h>
#include <stdio.h>
#include <locale.h>
#include <time.h>
#include <unistd.h> // usleep
#define BUF_SIZE 256
#define DELAY_MILLISECONDS 1000
const struct tm *now() {
// retrieve time since epoch
const time_t now_as_time_t = time(NULL);
if (now_as_time_t == -1) {
fprintf(stderr, "Error: could not get local time");
return NULL;
}
// convert to local time
const struct tm *now_as_tm = localtime(&now_as_time_t);
if (!now_as_tm)
perror("could not convert local time");
return now_as_tm;
}
char buf[BUF_SIZE];
int main(int argc, char *argv[]) {
// set given locale if it exists, or default to "C"
if (argc == 2)
if (!setlocale(LC_TIME, argv[1])) {
fprintf(stderr, "Error: could not set locale: '%s'", argv[1]);
return EXIT_FAILURE;
}
const struct tm *time_now;
size_t n;
// loop forever (kill process with ^C), printing the current date and time every second
while ((time_now = now())
&& (n = strftime(buf, sizeof buf, "%A %c", time_now))) {
printf("\r%s", buf); // overwrites the current console line thanks to '\r'
fflush(stdout);
usleep(DELAY_MILLISECONDS * 1000); // takes µseconds
}
if (n == 0)
fprintf(stderr, "Error: could not stringify local time");
return EXIT_FAILURE;
} |
Partager