diff options
author | John Ankarström <john@ankarstrom.se> | 2021-07-12 17:30:47 +0200 |
---|---|---|
committer | John Ankarström <john@ankarstrom.se> | 2021-07-12 17:30:47 +0200 |
commit | af7821da81932a990ecc64a6381a90f3d6eaf5d2 (patch) | |
tree | eb7c1dfe291b2daaaa6a72669578faa3dc5ca8e6 | |
parent | ede252c175859041bfddf36983c4672bd756ecaa (diff) | |
download | xutil-af7821da81932a990ecc64a6381a90f3d6eaf5d2.tar.gz |
ce: Rewrite in C
The `build' program is available at
http://git.ankarstrom.se/build/
-rw-r--r-- | Makefile | 3 | ||||
-rwxr-xr-x | etc/ce | 28 | ||||
-rw-r--r-- | etc/ce.c | 44 |
3 files changed, 47 insertions, 28 deletions
@@ -8,3 +8,6 @@ install: @install $(EXEC) /usr/local/bin @echo Rewriting shebangs... @re! $(IEXEC) + +build: + build */*.c @@ -1,28 +0,0 @@ -#!/bin/sh - -# ce -- center text - -usage() { echo usage: $0 [cols] 1>&2; exit 1; } - -[ $# -gt 1 ] && usage - -if [ $# -eq 1 ]; then - cols=${1#-} - [ "$cols" -gt 0 ] || usage - shift -else - cols=`tput cols` - [ "$cols" -le 80 ] || cols=80 -fi - -while read line; do - line=${line## } - line=${line%% } - len=`echo "$line" | wc -c` - max=$(((cols - len) / 2)) - i=0 - while [ $((i++)) -lt $max ]; do - printf ' ' - done - echo "$line" -done diff --git a/etc/ce.c b/etc/ce.c new file mode 100644 index 0000000..c8981bd --- /dev/null +++ b/etc/ce.c @@ -0,0 +1,44 @@ +/* + * ce -- center text + * $ cc -O2 -o ce ce.c + */ + +#include <err.h> +#include <ctype.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define MAXBUF 255 + +int +main(int argc, char *argv[]) +{ + char *buf; + int cols, i, max; + + if(argc-1 > 1){ + fprintf(stderr, "usage: %s [cols]\n", argv[0]); + return 1; + } + cols = argv[1] ? atoi(argv[1]) : 80; + + if(!(buf = malloc(MAXBUF))) + err(1, "malloc"); + + while(fgets(buf, MAXBUF, stdin)){ + buf[strcspn(buf, "\n")] = 0; + + /* Remove leading and trailing whitespace. */ + for (; *buf; buf++) + if(!isspace(*buf)) break; + for (i = strlen(buf)-1; i >= 0; i--) + if(!isspace(buf[i])) break; + buf[i+1] = 0; + + /* Calculate number of spaces. */ + max = cols/2 + strlen(buf)/2; + + printf("%*s\n", max, buf); + } +} |