root/wc.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. wc
  2. main

   1 #include "types.h"
   2 #include "stat.h"
   3 #include "user.h"
   4 
   5 char buf[512];
   6 
   7 void
   8 wc(int fd, char *name)
   9 {
  10   int i, n;
  11   int l, w, c, inword;
  12 
  13   l = w = c = 0;
  14   inword = 0;
  15   while((n = read(fd, buf, sizeof(buf))) > 0){
  16     for(i=0; i<n; i++){
  17       c++;
  18       if(buf[i] == '\n')
  19         l++;
  20       if(strchr(" \r\t\n\v", buf[i]))
  21         inword = 0;
  22       else if(!inword){
  23         w++;
  24         inword = 1;
  25       }
  26     }
  27   }
  28   if(n < 0){
  29     printf(1, "wc: read error\n");
  30     exit();
  31   }
  32   printf(1, "%d %d %d %s\n", l, w, c, name);
  33 }
  34 
  35 int
  36 main(int argc, char *argv[])
  37 {
  38   int fd, i;
  39 
  40   if(argc <= 1){
  41     wc(0, "");
  42     exit();
  43   }
  44 
  45   for(i = 1; i < argc; i++){
  46     if((fd = open(argv[i], 0)) < 0){
  47       printf(1, "wc: cannot open %s\n", argv[i]);
  48       exit();
  49     }
  50     wc(fd, argv[i]);
  51     close(fd);
  52   }
  53   exit();
  54 }

/* [<][>][^][v][top][bottom][index][help] */