Skip to content

Instantly share code, notes, and snippets.

@makunomark
Created January 17, 2018 06:33
Show Gist options
  • Save makunomark/0631628248ee4a203c539092eb6b9337 to your computer and use it in GitHub Desktop.
Save makunomark/0631628248ee4a203c539092eb6b9337 to your computer and use it in GitHub Desktop.
%{
int in_string_array(char*, char**, int);
char **words;
int words_count = 0;
%}
%%
/* Match all words */
[^ \t\n]+ {
//Check if word already exists
if(!in_string_array(yytext, words, words_count)){
words = (char**)realloc(words, (words_count+1)*sizeof(*words)); //Expanding array size dynamically
//sizeof(char*) is 8 bits for 64-bit, 4 bits for 32-bit
//allocate memory in word list for new word
words[words_count] = (char*)malloc(sizeof(yytext));
//copy new word into word list
strcpy(words[words_count], yytext);
words_count++;
}
}
/* Match nothing else */
. ;
\n ;
%%
int in_string_array(char *word, char **words, int words_length){
// Checks if the specified string is in the string array
int i;
for(i = 0; i < words_length; i++){
if(strcmp(word, words[i]) == 0){
return 1;
}
}
// No match found
return 0;
}
int main(int argc, char *argv[]){
yyin = fopen(argv[1], "r");
yylex();
int total_words = words_count;
int i;
for(i = 0; i < total_words; i++){
printf("%d - %s\n", i + 1, words[i]);
}
printf("\n\nTotal unique words: %d\n\n", total_words);
fclose(yyin);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment