Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c - 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
");
    exit(-1);
}

scanf("%s",word);

printf("%s
", word);

while(!feof(in_file))//this loop searches the for the current word
{
    fscanf(in_file,"%s",string);
    if(!strcmp(string,word))//if match found increment num
    num++;
}
printf("we found the word %s in the file %d times
",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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...