Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- > ./main cat nap dog
- Given input:
- cat
- .
- Expected output:
- Looking for 3 words
- Result:
- cat:1
- nap:0
- dog:0
- #define LENGTH(s) (sizeof(s) / sizeof(*s))
- /* Structures */
- typedef struct {
- char *word;
- int counter;
- } WordCountEntry;
- int process_stream(WordCountEntry entries[], int entry_count)
- {
- short line_count = 0;
- char buffer[30];
- while (fgets(buffer,sizeof(buffer),stdin)) {
- if (*buffer == '.')
- break;
- /* Compare against each entry */
- int i = 0;
- while (i < entry_count) {
- if (!strcmp(entries[i].word, buffer))
- entries[i].counter++;
- i++;
- }
- line_count++;
- }
- return line_count;
- }
- void print_result(WordCountEntry entries[], int entry_count)
- {
- fprintf(stdout,"Result:n");
- for(int i=0; i <=entry_count;i++){
- printf("%s:%dn", entries[i].word, entries[i].counter);
- }
- }
- void printHelp(const char *name)
- {
- fprintf(stderr,"usage: %s [-h] <word1> ... <wordN>n", name);
- }
- int main(int argc, char **argv)
- {
- const char *prog_name = *argv;
- WordCountEntry entries[argc];
- int entryCount = 0;
- while ((*argv) != NULL) {
- if (**argv == '-') {
- switch ((*argv)[1]) {
- case 'h':
- printHelp(prog_name);
- break;
- case'f':
- freopen((*argv)[2],"w",stdout);
- break;
- default:
- fprintf(stderr,"%s: Invalid option %s. Use -h for help.n",
- prog_name, *argv);
- }
- } else {
- if (entryCount < argc-1) {
- entries[entryCount].word = *argv;
- entries[entryCount++].counter = 0;
- }
- }
- argv++;
- }
- if (entryCount == 0) {
- fprintf(stderr,"%s: Please supply at least one word. Use -h for help.n",
- prog_name);
- return EXIT_FAILURE;
- }
- if (entryCount == 1) {
- fprintf(stdout,"Looking for a single wordn");
- } else {
- fprintf(stdout,"Looking for %d wordsn", entryCount);
- }
- process_stream(entries, entryCount);
- print_result(entries, entryCount);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement