www.digitalmars.com Home | Search | D
Last update Thu May 19 2005
D
Language
Phobos
Comparisons

· Overview
· D for Win32
· Win32 DLLs in D
· C .h to D Modules
· FAQ
· Style Guide
· Example: wc
· Future
· D Change Log
· Tech Tips
· Glossary
· Acknowledgements

Tools
· DMD D Compiler
· GDC D Compiler
· Linker
· Profiler

Community
· News Digest
· News
· Forum
· Announcements
· Learn
· D links

Archives
· digitalmars.D
· digitalmars.D.dtl
· digitalmars.D.announce
· digitalmars.D.learn
· digitalmars.D.bugs
· D.gnu
· Old D

Example: wc

This program is the D version of the classic wc (wordcount) C program. It serves to demonstrate how to read files, slice arrays, and simple symbol table management with associative arrays.

import std.file;

int main (char[][] args)
{
    int w_total;
    int l_total;
    int c_total;

    printf ("   lines   words   bytes file\n");
    foreach (char[] arg; args[1 .. args.length])
    {
	char[] input;
	int w_cnt, l_cnt, c_cnt;
	int inword;

	input = cast(char[])std.file.read(arg);

	foreach (char c; input)
	{
	    if (c == '\n')
		++l_cnt;
	    if (c != ' ')
	    {
		if (!inword)
		{
		    inword = 1;
		    ++w_cnt;
		}
	    }
	    else
		inword = 0;
	    ++c_cnt;
	}
	printf ("%8lu%8lu%8lu %.*s\n", l_cnt, w_cnt, c_cnt, arg);
	l_total += l_cnt;
	w_total += w_cnt;
	c_total += c_cnt;
    }
    if (args.length > 2)
    {
	printf ("--------------------------------------\n%8lu%8lu%8lu total",
	    l_total, w_total, c_total);
    }
    return 0;
}

Feedback and Comments

Add feedback and comments regarding this page.