Exit show-time if terminal width is unknown.
[show-time.git] / show-time.c
1
2 #include <stdio.h>
3 #include <sys/ioctl.h>
4 #include <time.h>
5 #include <string.h>
6 #include <unistd.h>
7
8 #define false 0
9 #define true (!false)
10 #define null 0
11
12 int getColumns() {
13         struct winsize terminalSize;
14         int error;
15
16         error = ioctl(1, TIOCGWINSZ, &terminalSize);
17
18         if (!error) {
19                 return terminalSize.ws_col;
20         }
21         return -1;
22 }
23
24 int main(int argc, char** argv) {
25         
26         struct tm *localTime;
27         time_t currentTime;
28         char buffer[80];
29         int terminalWidth;
30
31         if (fork() != 0) {
32                 return 0;
33         }
34
35         while (true) {
36                 currentTime = time(null);
37                 localTime = localtime(&currentTime);
38                 strftime(buffer, 80, "%d.%m.%Y %H:%M:%S", localTime);
39                 printf("%c[s", 27); /* save cursor position */
40                 terminalWidth = getColumns();
41                 if (terminalWidth == -1) {
42                         return 0;
43                 }
44                 printf("%c[%d;%dH", 27, 1, (int) (terminalWidth - strlen(buffer))); /* set cursor */
45                 printf("%s", buffer);
46                 printf("%c[u", 27); /* restore cursor position */
47                 fflush(stdout);
48                 sleep(1);
49         }
50
51 }
52