cal.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2019 K. Lange
  5. *
  6. * cal - print a calendar
  7. */
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <time.h>
  11. #include <unistd.h>
  12. #include <sys/time.h>
  13. const char * month_names[] = {
  14. "January",
  15. "February",
  16. "March",
  17. "April",
  18. "May",
  19. "June",
  20. "July",
  21. "August",
  22. "September",
  23. "October",
  24. "November",
  25. "December",
  26. };
  27. int days_in_months[] = {
  28. 31, 0, 31, 30, 31, 30, 31,
  29. 31, 30, 31, 30, 31,
  30. };
  31. int main(int argc, char * argv[]) {
  32. if (argc > 1) {
  33. fprintf(stderr, "%s: arguments not currently supported\n", argv[0]);
  34. return 1;
  35. }
  36. struct timeval now;
  37. gettimeofday(&now, NULL);
  38. struct tm actual;
  39. struct tm * timeinfo;
  40. timeinfo = localtime((time_t *)&now.tv_sec);
  41. memcpy(&actual, timeinfo, sizeof(struct tm));
  42. timeinfo = &actual;
  43. char month[20];
  44. sprintf(month, "%s %d", month_names[timeinfo->tm_mon], timeinfo->tm_year + 1900);
  45. int len = (20 - strlen(month)) / 2;
  46. while (len > 0) {
  47. printf(" ");
  48. len--;
  49. }
  50. /* Heading */
  51. printf("%s\n", month);
  52. printf("Su Mo Tu We Th Fr Sa\n");
  53. /* Now's the fun part. */
  54. int days_in_month = days_in_months[timeinfo->tm_mon];
  55. if (days_in_month == 0) {
  56. /* How many days in February? */
  57. struct tm tmp;
  58. memcpy(&tmp, timeinfo, sizeof(struct tm));
  59. tmp.tm_mday = 29;
  60. tmp.tm_hour = 12;
  61. time_t tmp3 = mktime(&tmp);
  62. struct tm * tmp2 = localtime(&tmp3);
  63. if (tmp2->tm_mday == 29) {
  64. days_in_month = 29;
  65. } else {
  66. days_in_month = 28;
  67. }
  68. }
  69. int mday = timeinfo->tm_mday;
  70. int wday = timeinfo->tm_wday; /* 0 == sunday */
  71. while (mday > 1) {
  72. mday--;
  73. wday = (wday + 6) % 7;
  74. }
  75. for (int i = 0; i < wday; ++i) {
  76. printf(" ");
  77. }
  78. while (mday <= days_in_month) {
  79. if (mday == timeinfo->tm_mday) {
  80. printf("\033[7m%2d\033[0m ", mday);
  81. } else {
  82. printf("%2d ", mday);
  83. }
  84. if (wday == 6) {
  85. printf("\n");
  86. }
  87. mday += 1;
  88. wday = (wday + 1) % 7;
  89. }
  90. if (wday != 0) {
  91. printf("\n");
  92. }
  93. return 0;
  94. }