changeset 662:5cb41d56f9d3

Posix compliance: wc shouldn't have trailing spaces (breaks aboriginal's mkinitr amfs script), when to print filenames was wrong, and it should have a "total" line when counting multiple arguments.
author Rob Landley <rob@landley.net>
date Thu, 06 Sep 2012 03:10:18 -0500
parents 12cf7e635f82
children 60cbc87c4314
files toys/posix/wc.c
diffstat 1 files changed, 23 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/toys/posix/wc.c	Mon Sep 03 21:25:46 2012 -0500
+++ b/toys/posix/wc.c	Thu Sep 06 03:10:18 2012 -0500
@@ -26,6 +26,26 @@
 
 #include "toys.h"
 
+DEFINE_GLOBALS(
+	unsigned long totals[3];
+)
+
+#define TT this.wc
+
+static void show_lengths(unsigned long *lengths, char *name)
+{
+	int i, nospace = 1;
+	for (i=0; i<3; i++) {
+		if (!toys.optflags || (toys.optflags&(1<<i))) {
+			xprintf(" %ld"+nospace, lengths[i]);
+			nospace = 0;
+		}
+		TT.totals[i] += lengths[i];
+	}
+	if (*toys.optargs) xprintf(" %s", name);
+	xputc('\n');
+}
+
 static void do_wc(int fd, char *name)
 {
 	int i, len;
@@ -48,13 +68,12 @@
 			lengths[2]++;
 		}
 	}
-	for (i=0; i<3; i++)
-		if (!toys.optflags || (toys.optflags&(1<<i)))
-			printf("%ld ", lengths[i]);
-	printf("%s\n", (!toys.optflags && strcmp(name,"-")) ? name : "");
+
+	show_lengths(lengths, name);
 }
 
 void wc_main(void)
 {
 	loopfiles(toys.optargs, do_wc);
+	if (toys.optc>1) show_lengths(TT.totals, "total");
 }