Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to count search words (keywords) in a text file in C

1 Answer

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

int main(void)
{
    const char  words[6][20] = { "stripos", "click", "substr", "save", "search", "sizeof" };
    char       *p = NULL;
    char        line[256], file[20] = "d:\\url.php";
    int         count[6] = { 0 };
    FILE       *fp;
    int         i;

    if ( !(fp = fopen(file, "r")) )
    {
        printf("Error open file: %s", file);
        return 1;
    }

    while (fgets(line, sizeof(line), fp))
      for (i = 0, p = line; i < 6; i++, p = line)
        while ( (p = strstr(p, words[i])) )
        {
            p = p + strlen(words[i]);
            count[i]++;
        }

    fclose(fp);
    
    for (i = 0; i < 6; i++)
        printf("The word: %-10s appear %3d times in file: %s\n", words[i], count[i], file);

    return 0;
}


/*
run:
 
The word: stripos    appear   5 times in file: d:\url.php
The word: click      appear  50 times in file: d:\url.php
The word: substr     appear  14 times in file: d:\url.php
The word: save       appear   4 times in file: d:\url.php
The word: search     appear   7 times in file: d:\url.php
The word: sizeof     appear   2 times in file: d:\url.php

*/


answered Mar 9, 2015 by avibootz
edited Mar 11, 2015 by avibootz

Related questions

1 answer 174 views
1 answer 175 views
1 answer 291 views
1 answer 161 views
1 answer 163 views
1 answer 158 views
1 answer 225 views
225 views asked Apr 8, 2015 by avibootz
...