Re: [hackers] [PATCH][sbase] cal: Centre month and year above calendar
Thanks for looking at this. The output looks much nice when centered.
On 2019-04-27, Richard Ipsum <richardipsum_AT_fastmail.co.uk> wrote:
> ---
> cal.c | 15 +++++++++------
> 1 file changed, 9 insertions(+), 6 deletions(-)
>
> diff --git a/cal.c b/cal.c
> index bf4f537..d347113 100644
> --- a/cal.c
> +++ b/cal.c
> _AT_@ -3,6 +3,7 @@
> #include <stdint.h>
> #include <stdio.h>
> #include <stdlib.h>
> +#include <string.h>
> #include <time.h>
> #include <unistd.h>
>
> _AT_@ -93,12 +94,13 @@ printgrid(size_t year, int month, int fday, int line)
> static void
> drawcal(size_t year, int month, size_t ncols, size_t nmons, int fday)
> {
> - char *smon[] = {" January", " February", " March", " April",
> - " May", " June", " July", " August",
> - "September", " October", " November", " December" };
> + char *smon[] = { "January", "February", "March", "April",
> + "May", "June", "July", "August",
> + "September", "October", "November", "December" };
> char *days[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", };
> size_t m, n, col, cur_year, cur_month, dow;
> - int line;
> + int line, width_d, width = sizeof("Su Mo Tu We Th Fr Sa") - 1;
> + char month_year[width + 1];
I think we can avoid the VLA here by rearranging a bit.
char month_year[sizeof("Su Mo Tu We Th Fr Sa")]; /* or maybe just,
3 * LEN(days) - 1 */
int width = sizeof(month_year) - 1;
but then, I don't think there is a need for a width variable, we could
just use sizeof(month_year) below.
>
> for (m = 0; m < nmons; ) {
> n = m;
> _AT_@ -109,8 +111,9 @@ drawcal(size_t year, int month, size_t ncols, size_t
> nmons, int fday)
> cur_month -= 12;
> cur_year += 1;
> }
> - printf(" %s %-4zu ", smon[cur_month], cur_year);
> - printf(" ");
> + snprintf(month_year, sizeof(month_year), "%s %zu", smon[cur_month],
> cur_year);
> + width_d = width - strlen(month_year);
> + printf("%*s%s%*s ", width_d / 2 + width_d % 2, "", month_year, width_d
> / 2, "");
Maybe we could just use a single variable `pad`
pad = sizeof(month_year) - strlen(month_year) - 1;
printf("%*s%s%*s ", pad / 2 + pad % 2, "", month_year, pad / 2, "");
> }
> putchar('\n');
> for (col = 0, m = n; m < nmons && col < ncols; ++col, ++m) {
> --
> 2.21.0
Received on Sun Apr 28 2019 - 21:02:53 CEST
This archive was generated by hypermail 2.3.0
: Sun Apr 28 2019 - 21:12:22 CEST