Wednesday, May 30, 2018

A Lex program to count number of words, lines and characters of given input file.

Input: file.txt

hi
HELLO
how are you

wordcount.l

%{
    #include<stdio.h>
    int cletter=0,sletter=0,lines=0,spaces=0,num=0,chara=0,words=0;
%}

%%
[\t ' ']+ {words++; spaces++; chara=chara+yyleng;}
\n  {lines++; words++;}
[A-Z] cletter++;
[a-z] sletter++;
[0-9] num++;
%%

main(){
    yyin=fopen("file.txt","r");
    yylex();
    printf("FILE HAS \n");
    printf("%d spaces",spaces);
    printf("\n");
    printf("%d words",words);
    printf("\n");
    printf("%d characters",chara);
    printf("\n");
    printf("%d  numbers",num);
    printf("\n");
    printf("%d  upper case letters",cletter);
    printf("\n");
    printf("%d  lower case letters",sletter);
    printf("\n");
    printf("%d  lines",lines);
    return 0;
}

int yywrap(){
    return (1);
}

Output

 



No comments:

Post a Comment