Mercurial > hg > toybox
annotate toys/wc.c @ 396:7ca3bef07f0d
Implement truncate.
author | Rob Landley <rob@landley.net> |
---|---|
date | Sun, 11 Dec 2011 03:58:43 -0600 |
parents | 67b0ded3c56c |
children |
rev | line source |
---|---|
386 | 1 /* vi: set sw=4 ts=4: |
2 * | |
387
67b0ded3c56c
Add dirname, and typo fixes to wc header.
Rob Landley <rob@landley.net>
parents:
386
diff
changeset
|
3 * wc.c - Word count |
386 | 4 * |
387
67b0ded3c56c
Add dirname, and typo fixes to wc header.
Rob Landley <rob@landley.net>
parents:
386
diff
changeset
|
5 * Copyright 2011 Rob Landley <rob@landley.net> |
386 | 6 * |
7 * See http://opengroup.org/onlinepubs/9699919799/utilities/wc.html | |
8 | |
9 USE_WC(NEWTOY(wc, "cwl", TOYFLAG_USR|TOYFLAG_BIN)) | |
10 | |
11 config WC | |
12 bool "wc" | |
13 default y | |
14 help | |
15 usage: wc -lwc [FILE...] | |
16 | |
17 Count lines, words, and characters in input. | |
18 | |
19 -l show lines | |
20 -w show words | |
21 -c show characters | |
22 | |
23 By default outputs lines, words, characters, and filename for each | |
24 argument (or from stdin if none). | |
25 */ | |
26 | |
27 #include "toys.h" | |
28 | |
29 static void do_wc(int fd, char *name) | |
30 { | |
31 int i, len; | |
32 unsigned long word=0, lengths[]={0,0,0}; | |
33 | |
34 for (;;) { | |
35 len = read(fd, toybuf, sizeof(toybuf)); | |
36 if (len<0) { | |
37 perror_msg("%s",name); | |
38 toys.exitval = EXIT_FAILURE; | |
39 } | |
40 if (len<1) break; | |
41 for (i=0; i<len; i++) { | |
42 if (toybuf[i]==10) lengths[0]++; | |
43 if (isspace(toybuf[i])) word=0; | |
44 else { | |
45 if (!word) lengths[1]++; | |
46 word=1; | |
47 } | |
48 lengths[2]++; | |
49 } | |
50 } | |
51 for (i=0; i<3; i++) | |
52 if (!toys.optflags || (toys.optflags&(1<<i))) | |
53 printf("%ld ", lengths[i]); | |
54 printf("%s\n", (!toys.optflags && strcmp(name,"-")) ? name : ""); | |
55 } | |
56 | |
57 void wc_main(void) | |
58 { | |
59 loopfiles(toys.optargs, do_wc); | |
60 } |