www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - small bug in wc sample

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;
            case 2*WORD + true:
              state= SPACE;

        // 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