啊~还有多长时间才能下班啊……
终端执行命令加上预计下班打卡时间,你就能知道自己还有多长时间才能下班了~(每分钟刷新屏幕哦)
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#define STR_LEN 32 // Max size of message to be printed
static int win_width = 0; // Width of terminal
static int win_height = 0; // Height of terminal
void getTerminalSize();
void target_trans(char *target, int *h, int *m);
void current_trans(int *h, int *m);
void print_countdown(int th, int tm, int ch, int cm); // t means target, c means current
void print_align_center(char *message);
int main(int argc, char **argv) {
if (argc != 2) return -1;
char* target = argv[argc - 1];
getTerminalSize();
int target_h = 0;
int target_m = 0;
target_trans(target, &target_h, &target_m);
int current_h = 0;
int current_m = 0;
current_trans(¤t_h, ¤t_m);
print_countdown(target_h, target_m, current_h, current_m);
while ((current_h != target_h) || (current_m != target_m)) {
int tmp_h = 0;
int tmp_m = 0;
current_trans(&tmp_h, &tmp_m);
if (tmp_m != current_m) {
current_h = tmp_h;
current_m = tmp_m;
print_countdown(target_h, target_m, current_h, current_m);
}
sleep(5);
}
return 0;
}
void getTerminalSize() {
struct winsize size;
ioctl(STDIN_FILENO, TIOCGWINSZ, &size);
win_width = size.ws_col;
win_height = size.ws_row;
}
// Transfer target time string to hour and minute
void target_trans(char *target, int *h, int *m) {
int *cur = h;
for (int i = 0; i < strlen(target); i++) {
if (target[i] == ':') {
cur = m;
continue;
}
(*cur) *= 10;
(*cur) += target[i] - '0';
}
}
// Get current time
void current_trans(int *h, int *m) {
time_t cur;
time(&cur);
struct tm *p = localtime(&cur);
(*h) = p->tm_hour;
(*m) = p->tm_min;
}
void print_countdown(int th, int tm, int ch, int cm) {
int sh = th - ch;
int sm = tm - cm;
if (sm < 0) {
sh--;
sm += 60;
}
if (sh < 0) sh += 24;
system("clear");
char message[STR_LEN];
if ((sh == 0) && (sm == 0)) {
snprintf(message, STR_LEN, "下班!!");
} else {
snprintf(message, STR_LEN, "距下班还有 %d:%d", sh, sm);
}
print_align_center(message);
}
void print_align_center(char *message) {
for (int i = 0; i < (win_height / 2); i++) printf("\n");
for (int j = 0; j < ((win_width - strlen(message)) / 2); j++) printf(" ");
printf("%s", message);
for (int i = 0; i < (win_height / 2); i++) printf("\n");
}
编译
gcc main.c -o CountDown
执行
$ ./CountDown xx:xx
结果