#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 20
#define TOTALWORDS 300
int countOccurrencesAllWords(char file[], char words[][LEN], int count[]) {
FILE *fp = fopen(file, "r");
if (fp == NULL) {
printf("Error open file\n");
exit(EXIT_FAILURE);
}
int wordindex = 0;
char word[20] = "";
while (fscanf(fp, "%s", word) != EOF) {
int i;
int notInArray = 1;
for (i = 0; i < wordindex && notInArray; i++) {
if (strcmp(words[i], word) == 0) {
notInArray = 0;
}
}
if (notInArray) {
strcpy(words[wordindex], word);
count[wordindex]++;
wordindex++;
}
else {
count[i - 1]++;
}
}
fclose(fp);
return wordindex; // totalwords
}
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 words[TOTALWORDS][LEN] = {"", ""};
int count[TOTALWORDS] = { 0 };
readFile(file);
puts("\n");
int totalwords = countOccurrencesAllWords(file, words, count);
for (int i = 0; i < totalwords; i++) {
printf("%s: %d times\n", words[i], count[i]);
}
return 0;
}
/*
run:
c cpp python csharp
php java c python
javascript python php
c: 2 times
cpp: 1 times
python: 3 times
csharp: 1 times
php: 2 times
java: 1 times
javascript: 1 times
*/