undone98 undone98 - 1 year ago 70
C Question

Program to read words from a file and count their occurrence in the file

I'm currently trying to make a program that will read a file find each unique word and count the number of times that word appears in the file. What I have currently ask the user for a word and searches the file for the number of times that word appears. However I need the program to read the file by itself instead of asking the user for an individual word.

This is what I have currently:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
int num =0;
char word[2000];
char *string;

FILE *in_file = fopen("words.txt", "r");

if (in_file == NULL)
printf("Error file missing\n");


printf("%s\n", word);

while(!feof(in_file))//this loop searches the for the current word
if(!strcmp(string,word))//if match found increment num
printf("we found the word %s in the file %d times\n",word,num );
return 0;

I just need some help figuring out how to read the file for unique words (words it hasn't checked for yet) although any other suggestions for my program will be appreciated.

md5 md5
Answer Source

If you want to print every line contained in the file just once, you have to save the strings you have read in a given data structure. For example, a sorted array could do the trick. The code might look as follow:

#include <stddef.h>

size_t numberOfLine = getNumberOfLine (file);
char **previousStrings = allocArray (numberOfLine, maxStringSize);
size_t i;

for (i = 0; i < numberOfLine; i++)
    char *currentString = readNextLine (file);

    if (!containString (previousStrings, currentString))
        printString (currentString);
        insertString (previousStrings, currentString);

You may use binary search to code the functions containString and insertString in an efficient way. See here for further informations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download