How to count the occurrences of a word in text file with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int countOccurrences(char file[], char *word) {
    FILE *fp = fopen(file, "r");  
	
	if (fp == NULL) {
        printf("Error open file\n");
        exit(EXIT_FAILURE);
    }
	
	char s[100];
    char *pos;
	int count = 0;

    while ((fgets(s, 100, fp)) != NULL) {
		int i = 0;
        while ((pos = strstr(s + i, word)) != NULL) {
            i = (pos - s) + 1;
            count++;
        }
    }

	fclose(fp);

    return count;
}
    
void readFile(char file[]) {
    FILE *fp = fopen(file, "r");
           
    char ch;
    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);
    
    fclose(fp);
}
      
int main()
{
    char file[100] = "d:\\data.txt";
    char word[30] = "python";
	
	readFile(file);
	
	printf("\n\n%d\n", countOccurrences(file, word));
	printf("%d\n", countOccurrences(file, "c++"));
		
	return 0;
}
       
         
         
         
/*
run:
         
c c++ python c#
java python
javascript python php

3
1
      
*/

 



answered Jul 9, 2020 by avibootz

Related questions

1 answer 53 views
1 answer 199 views
1 answer 151 views
1 answer 147 views
1 answer 141 views
1 answer 144 views
1 answer 150 views
...