digitalmars.D.bugs - small bug in wc sample
- Manfred Nowak (58/58) Dec 04 2005 Usual understanding is, that newLines are white space and therefore
Usual understanding is, that newLines are white space and therefore
word separators.
The wc.d in the samples of DMD does not take this into account.
So I rewrote it, mostly not to fix that bug, but to see how the
beautifulness of D would show up.
As always: love it, leave it or change it :-)
import std.file, std.stdio;
void main (char[][] args) {
struct Count{
uint bytes= 0, words= 0, lines= 0;
void opAddAssign( Count right){
bytes+= right.bytes;
words+= right.words;
lines+= right.lines;
}
} Count total;
writefln( " lines words bytes file");
// foreach file
foreach( char[] arg; args[1 .. args.length]) {
char[] input= cast(char[]) std.file.read(arg);
Count current;
// compute byte count
current.bytes= input.length;
// compute word count
enum{ SPACE, WORD};
int state= SPACE;
foreach( char c; input){
bit isSpace= ( c == ' ' || c == '\n');
switch( 2*state + isSpace){
case 2*SPACE + false:
state= WORD;
current.words++;
break;
case 2*WORD + true:
state= SPACE;
break;
default:
break;
}
}
// compute line count
foreach ( char c; input){
bit isEOL= ( c == '\n');
current.lines+= isEOL;
}
writefln( "%8d%8d%8d %s",
current.lines, current.words, current.bytes, arg);
// sum up
total+= current;
}
if( args.length > 2){
writefln( "--------------------------------------
%8d%8d%8d total",
total.lines, total.words, total.bytes);
}
}
Dec 04 2005








Manfred Nowak <svv1999 hotmail.com>