jLynx
jLynx

Reputation: 1149

Finding occurrences of specific word line by line from text file

I'm trying to read out my text file line by line

FILE *infile;
char line[1000];
infile = fopen("file.txt","r");
while(fgets(line,1000,infile) != NULL) 
{
    //....
}
fclose(infile);

And then I need to find a specific word, for example "the", and need to see how many time it occurs and what lines it also occurs on.

I should be able to count the words with this

int wordTimes = 0;
if((strcmp("the", currentWord) == 0)) 
{
    printf("'%s' appears in line %d  which is: \n%s\n\n", "the", line_num, line);
    wordTimes++;
}

where line is the line of text that the string occurs on and line_num is the line number that it occurs on.

And then the amount of times the word is shown uses this code:

if(wordTimes > 0)
{
    printf("'%s' appears %d times\n", "the", wordTimes);
}
else
{
    printf("'%s' does not appear\n", "the");
}

The problem is that I'm not sure how to compare each word in the line to "the" and still print out the line it applies on.

I have to use very basic C for this, so that means I can't use strtok() or strstr(). I can only use strlen() and strcmp().

Upvotes: 2

Views: 1446

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754790

Maybe you need to write a strword() function like this. I'm assuming you can use the classification functions (macros) from <ctype.h>, but there are workarounds if that isn't allowed either.

#include <assert.h>
#include <ctype.h>
#include <stdio.h>

char *strword(char *haystack, char *needle);

char *strword(char *haystack, char *needle)
{
    char *pos = haystack;
    char old_ch = ' ';
    while (*pos != '\0')
    {
        if (!isalpha(old_ch) && *pos == *needle)
        {
            char *txt = pos + 1;
            char *str = needle + 1;
            while (*txt == *str)
            {
                if (*str == '\0')
                    return pos;     // Exact match at end of haystack
                txt++, str++;
            }
            if (*str == '\0' && !isalpha(*txt))
                return pos;
        }
        old_ch = *pos++;
    }
    return 0;
}

int main(void)
{
    /*
    ** Note that 'the' appears in the haystack as a prefix to a word,
    ** wholly contained in a word, and at the end of a word - and is not
    ** counted in any of those places. And punctuation is OK.
    */
    char haystack[] =
        "the way to blithely count the occurrences (tithe)"
        " of 'the' in their line is the";
    char needle[] = "the";

    char *curpos = haystack;
    char *word;
    int count = 0;
    while ((word = strword(curpos, needle)) != 0)
    {
        count++;
        printf("Found <%s> at [%.20s]\n", needle, word);
        curpos = word + 1;
    }

    printf("Found %d occurrences of <%s> in [%s]\n", count, needle, haystack);

    assert(strword("the", "the") != 0);
    assert(strword("th", "the") == 0);
    assert(strword("t", "t") != 0);
    assert(strword("", "t") == 0);
    assert(strword("if t fi", "t") != 0);
    assert(strword("if t fi", "") == 0);
    return 0;
}

When run, this produces:

Found <the> at [the way to blithely ]
Found <the> at [the occurrences (tit]
Found <the> at [the' in their line i]
Found <the> at [the]
Found 4 occurrences of <the> in [the way to blithely count the occurrences (tithe) of 'the' in their line is the]

Is there a way to do the strword function without <ctype.h>?

Yes. I said as much in the opening paragraph. Since the only function/macro used is isalpha(), you can make some assumptions (that you're not on a system using EBCDIC) so that the Latin alphabet is contiguous, and you can use this is_alpha() in place of isalpha() — and omit <ctype.h> from the list of included headers:

static inline int is_alpha(int c)
{
    return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}

Upvotes: 4

Related Questions