Next: , Previous: More Examples, Up: More Examples   [Contents][Index]


7.1 ñ¸ì¿ô¡¢Ê¸»ú¿ô¡¢¹Ô¿ô¤Î¥«¥¦¥ó¥È

°Ê²¼¤ÎÄêµÁ¤Ï¡¢ Í¿¤¨¤é¤ì¤¿¥Õ¥¡¥¤¥ë¤ÎÃæ¤Îñ¸ì¿ô¡¢Ê¸»ú¿ô¡¢¹Ô¿ô¤ò¥«¥¦¥ó¥È¤¹¤ë¤Î¤ËFlex¤ò»È¤¦ÊýË¡¤ò¼¨¤¹¡¢ ´Êñ¤ÊÎã¤Ç¤¹¡£ ¼ÂºÝ¤ËFlex¤Ë´Ø·¸¤Î¤¢¤ëÉôʬ¤Ï¡¢ Èó¾ï¤Ë¾¯¤Ê¤¤¤³¤È¤ËÃí°Õ¤·¤Æ¤¯¤À¤µ¤¤¡£ °Ê²¼¤Î¥³¡¼¥É¤Î¤Û¤È¤ó¤É¤Ï¡¢ ¥³¥Þ¥ó¥É¥é¥¤¥ó¡¦¥Ñ¥é¥á¡¼¥¿¤ò½èÍý¤·¤¿¤ê¡¢ ¥«¥¦¥ó¥È¤Î¹ç·×¤òÊÝ»ý¤·¤¿¤ê¤¹¤ë¤â¤Î¤Ç¤¹¡£

/*
 * wc.lex : wc¤Î¤è¤¦¤Ê¥æ¡¼¥Æ¥£¥ê¥Æ¥£¤ò¡¢
 *          Flex¤ò»È¤Ã¤ÆºîÀ®¤¹¤ë´Êñ¤ÊÎã
 */
%{
int  numchars = 0;
int  numwords = 0;
int  numlines = 0;
int  totchars = 0;
int  totwords = 0;
int  totlines = 0;
%}

/*
 * ¥ë¡¼¥ë¤Ï¤³¤³¤«¤é»Ï¤Þ¤ë
 */

%%

[\n]        { numchars++;  numlines++;         }
[^ \t\n]+   { numwords++;  numchars += yyleng; }
.           { numchars++;                      }

%%

/*
 * ÄɲÃŪ¤ÊC¥³¡¼¥É¤¬¤³¤³¤«¤é»Ï¤Þ¤ë¡£
 * ¤³¤³¤Ç¡¢¤¹¤Ù¤Æ¤Î°ú¿ô½èÍýÅù¤ò¹Ô¤¦¥³¡¼¥É¤¬Ä󶡤µ¤ì¤ë
 */

void main(int argc, char **argv)
{
  int  loop;
  int  lflag = 0; /* ¹Ô¿ô¤ò¥«¥¦¥ó¥È¤¹¤ë¾ì¹ç¤Ï1         */
  int  wflag = 0; /* ñ¸ì¿ô¤ò¥«¥¦¥ó¥È¤¹¤ë¾ì¹ç¤Ï1       */
  int  cflag = 0; /* ʸ»ú¿ô¤ò¥«¥¦¥ó¥È¤¹¤ë¾ì¹ç¤Ï1       */
  int  fflag = 0; /* ¥Õ¥¡¥¤¥ë̾¤¬»ØÄꤵ¤ì¤Æ¤¤¤ë¾ì¹ç¤Ï1 */

  for(loop=1; loop<argc; loop++){
     char *tmp = argv[loop];
     if(tmp[0] == '-'){
     switch(tmp[1]){
       case 'l':
          lflag = 1;
          break;
       case 'w':
          wflag = 1;
          break;
       case 'c':
          cflag = 1;
          break;
       default:
          fprintf(stderr,"unknown option -%c\n",tmp[1]);
     }
    } else {
      fflag = 1;
      numlines = numchars = numwords = 0;  
      if((yyin = fopen(tmp,"rb")) != 0){
        (void) yylex();
        fclose(yyin);
        totwords += numwords;
        totchars += numchars;
        totlines += numlines;
        printf("file  : %25s :",tmp) ;
        if(lflag){
          fprintf(stdout,"lines %5d ",numlines); 
        }
        if(cflag){
          fprintf(stdout,"characters %5d ",numchars); 
        }
        if(wflag){
          fprintf(stdout,"words %5d ",numwords); 
        }
        fprintf(stdout,"\n");
      }else{
        fprintf(stderr,"wc : file not found %s\n",tmp);
      } 
    }
  }
  if(!fflag){
    fprintf(stderr,"usage : wc [-l -w -c] file [file...]\n");
    fprintf(stderr,"-l = count lines\n");
    fprintf(stderr,"-c = count characters\n");
    fprintf(stderr,"-w = count words\n");
    exit(1);
  }
  for(loop=0;loop<79; loop++){
    fprintf(stdout,"-");
  }
  fprintf(stdout,"\n");
  fprintf(stdout,"total : %25s  ","") ;
  if(lflag){
    fprintf(stdout,"lines %5d ",totlines); 
  }
  if(cflag){
    fprintf(stdout,"characters %5d ",totchars); 
  }
  if(wflag){
     fprintf(stdout,"words %5d ",totwords); 
  }
  fprintf(stdout,"\n");
}