1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* get_word(char** data)
{
char* word = new char[strlen(*data)+1];
memset(word, 0, strlen(*data));
char* p = word;
while(*data)
{
if (isalpha(**data))
*(p++) = **data;
else
if (word[0])
break;
++*data;
}
return word;
}
void get_wordcount_and_matchcount(const char* data, const char* match, int* wordcount, int* matchcount)
{
char* p = (char*)data;
while(p && *p)
{
char* word = get_word(&p);
if (word)
{
++(*wordcount);
if (strcmp(match, word) == 0)
++(*matchcount);
delete[] word;
}
}
}
int main(int argc, char* argv[])
{
if (argc != 3)
return 1;
char* myword = argv[1];
FILE* file_input = fopen(argv[2], "r");
if (file_input)
{
fseek(file_input, 0, SEEK_END);
size_t size = ftell(file_input);
char* data = new char[size+1];
rewind(file_input);
fread(data, sizeof(char), size, file_input);
fclose(file_input);
data[size] = '\0';
int wordcount(0), matchcount(0);
get_wordcount_and_matchcount(data, myword, &wordcount, &matchcount);
printf("The number of words in input was: %d and the number of words that matched %s was: %d\n\n", wordcount, myword, matchcount);
delete[] data;
}
return 0;
}
|