Tip/Linux2025. 9. 9. 00:46

WordCount 예제

%{
    unsigned int charCount = 0, wordCount = 0, lineCount = 0;
%}

word [^ \t\n]+
eol  \n

%%
{word} { wordCount++; charCount += yyleng; }
{eol}  { charCount++; lineCount++; }
.      { charCount++; }
%%

int main(int argc, char **argv) {
        yylex();
        printf(" %d %d %d\n", lineCount, wordCount, charCount);
        return 0;
}

WordCount 예제 2 (파일에서 읽기)

%{
    unsigned int charCount = 0, wordCount = 0, lineCount = 0;
%}

word [^ \t\n]+
eol  \n

%%
{word} { wordCount++; charCount += yyleng; }
{eol}  { charCount++; lineCount++; }
.      { charCount++; }
%%

int main(int argc, char **argv) {
        FILE *file = NULL;
        if (argc > 1) {
                file = fopen(argv[1], "r");
                if (!file) {
                        fprintf(stderr, "Could not open %s\n", argv[1]);
                        exit(1);
                }
                yyin = file;
        }
        yylex();
        printf(" %d %d %d %s\n", lineCount, wordCount, charCount,
                        (file == NULL ? "" : argv[1]));
        return 0;
}

Posted by chobocho