%{
#include <stdio.h> #include <string.h>
int count = 0; // Counter to keep track of the word frequency char word[100]; // The target word to search for
%}
%%
{word
} { count
++; } // Increment the counter whenever the word
is found
.|\n ; // Ignore other characters
%%
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <filename> <word_to_search>\n", argv[0]); return 1;
}
FILE *file = fopen(argv[1], "r"); if (!file) {
printf
("Error
: Could not
open file
%s\n", argv[1]); return 1;}
strcpy(word, argv[2]); // Copy the target word to search into the global 'word' variable yyin = file; // Set the input stream to the file
yylex(); // Start the lexical analysis
printf("The word '%s' appears %d times in the file %s.\n", word, count, argv[1]);
fclose(file); return 0;
}
JXsKI2luY2x1ZGUgPHN0ZGlvLmg+ICNpbmNsdWRlIDxzdHJpbmcuaD4KCmludCBjb3VudCA9IDA7IC8vIENvdW50ZXIgdG8ga2VlcCB0cmFjayBvZiB0aGUgd29yZCBmcmVxdWVuY3kgY2hhciB3b3JkWzEwMF07IC8vIFRoZSB0YXJnZXQgd29yZCB0byBzZWFyY2ggZm9yCiV9CgolJQp7d29yZH0geyBjb3VudCsrOyB9IC8vIEluY3JlbWVudCB0aGUgY291bnRlciB3aGVuZXZlciB0aGUgd29yZCBpcyBmb3VuZAoufFxuIDsJLy8gSWdub3JlIG90aGVyIGNoYXJhY3RlcnMKJSUKCmludCBtYWluKGludCBhcmdjLCBjaGFyICphcmd2W10pIHsKIAoKaWYgKGFyZ2MgIT0gMykgewpwcmludGYoIlVzYWdlOiAlcyA8ZmlsZW5hbWU+IDx3b3JkX3RvX3NlYXJjaD5cbiIsIGFyZ3ZbMF0pOyByZXR1cm4gMTsKfQoKRklMRSAqZmlsZSA9IGZvcGVuKGFyZ3ZbMV0sICJyIik7IGlmICghZmlsZSkgewpwcmludGYoIkVycm9yOiBDb3VsZCBub3Qgb3BlbiBmaWxlICVzXG4iLCBhcmd2WzFdKTsgcmV0dXJuIDE7Cn0Kc3RyY3B5KHdvcmQsIGFyZ3ZbMl0pOyAvLyBDb3B5IHRoZ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