[PATCH] cols: simplify filling with spaces

From: Jakob Kramer <jakob.kramer_AT_gmx.de>
Date: Wed, 4 Jun 2014 17:46:22 +0200

Use printf("%*s", n, "") instead of allocating
a string filled with spaces.
---
 cols.c | 15 +++++----------
 1 file changed, 5 insertions(+), 10 deletions(-)
diff --git a/cols.c b/cols.c
index 411ce58..ca37414 100644
--- a/cols.c
+++ b/cols.c
_AT_@ -26,8 +26,8 @@ int
 main(int argc, char *argv[])
 {
 	long i, l, col;
-	size_t maxlen = 0;
-	char *space;
+	size_t len;
+	int maxlen = 0;
 	struct winsize w;
 	FILE *fp;
 
_AT_@ -59,7 +59,7 @@ main(int argc, char *argv[])
 	}
 
 	for(l = 0; l < b.nlines; ++l) {
-		size_t len = strlen(b.lines[l]);
+		len = strlen(b.lines[l]);
 		if(len > 0 && b.lines[l][len-1] == '\n')
 			b.lines[l][--len] = '\0';
 		if(len > maxlen)
_AT_@ -76,21 +76,16 @@ main(int argc, char *argv[])
 		return EXIT_SUCCESS;
 	}
 
-	if(!(space = malloc(maxlen + 2)))
-		eprintf("malloc:");
-	memset(space, ' ', maxlen + 1);
-	space[maxlen + 1] = '\0';
-
 	n_rows = (b.nlines + (n_columns - 1)) / n_columns;
 	for(i = 0; i < n_rows; ++i) {
 		for(l = i, col = 1; l < b.nlines; l += n_rows, ++col) {
+			len = strlen(b.lines[l]);
 			fputs(b.lines[l], stdout);
 			if(col < n_columns)
-				fputs(space + strlen(b.lines[l]), stdout);
+				printf("%*s", maxlen + 1 - (int)len, "");
 		}
 		fputs("\n", stdout);
 	}
-	free(space);
 
 	return EXIT_SUCCESS;
 }
-- 
1.8.5.1
--BOKacYhQ+x31HxR3--
Received on Mon Sep 17 2001 - 00:00:00 CEST

This archive was generated by hypermail 2.3.0 : Wed Jun 04 2014 - 18:24:10 CEST