-3

i am unable to get the specific words. the task is to count the number of lines and specific words present in a text file. i was unable to count the specific words present in the text file. could anyone help me with it. Thanks in advance. my code:

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



int main()
{
FILE *fp;
 char filename[100];
 char ch;
 int linecount, wordcount,count;


 linecount = 0;
 wordcount = 0;


  printf("Enter a filename :");
  gets(filename);


   fp = fopen(filename,"r");


   if ( fp )
   {

       while ((ch=getc(fp)) != EOF) {


           if (ch == ' ' || ch == '\n') { ++wordcount; }

      if (ch == '\n') { ++linecount; }

       }

       if (wordcount > 0) {
        ++linecount;
        ++wordcount;
       }
    }
   else
      {
         printf("failed to open the file\n");
        }

    printf("Lines : %d \n", linecount);
    printf("Words : %d \n", wordcount);

#define MAX_WORD_LENGTH 10

char word[MAX_WORD_LENGTH + 1];

while ( getNextWord( word, sizeof word,fp ))
{
  if ( match( word ) )
    count++;
}
 printf("total number of keywords %d",count);

return(0);
}

int getNextWord( char *target, size_t targetSize,FILE *fp )
{
  size_t i = 0;
  int c;

  while ( (c = fgetc( fp )) != EOF && i < targetSize - 1 )
  {
    if ( isspace( c ) )
    {
      if ( i == 0 )
        continue;
      else
        break;
    }
    else
    {
      target[i++] = c;
    }
  }

  target[i] = 0;
  return i > 0;
}

int match( const char *word )
{
  const char *targets[] = {"the","two",""};
  const char *t = targets;

 while ( *t[0] != '\0' && strcmp(*t, word))
    t++;

  return t[0] != '\0';
}



the task is to count the number of lines and specific words present in a text file. i was unable to count the specific words present in the text file. could anyone help me with it. Thanks in advance.

  • regarding: `gets(filename);` The function: `gets()` has been depreciated for years and completely removed in recent versions of the C standard. Strongly suggest using `fgets()` (which has a different set of parameters) – user3629249 Nov 03 '19 at 16:20
  • the function: `getc()` returns a `int`, not a `char` and (under most conditions) a `char` will not recognize a EOF (which is a -1 I.E. 0xffffffff. – user3629249 Nov 03 '19 at 16:22
  • regarding: `printf("failed to open the file\n");` Error messages should be output to `stderr`, not `stdout` and when the error is from a C library function, should also output the text reason the system thinks the error occurred. Suggest using: `perror( "fopen failed" );` as that function performs both activities. – user3629249 Nov 03 '19 at 16:35
  • When a call to `fopen()` fails, after a call to `perror()`, the best response to this kind of failure is to exit the program, usually via: `exit( EXIT_FAILURE );` Note: both `exit()` and EXIT_FAILURE are exposed via: `#include ` – user3629249 Nov 03 '19 at 16:37
  • OT: regarding: `if (ch == '\n') { ++linecount; }` Please follow the axiom: *only one statement per line and (at most) one variable declaration per statement.* – user3629249 Nov 03 '19 at 16:40

2 Answers2

0

You can make a struct to store information about word and occurrence of word.

struct dictionary
{
    char *word;
    int occurrence;
};
Maqcel
  • 493
  • 5
  • 16
0

The OPs posted code, when run through a C compiler, results in:

gcc    -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11  -c "untitled.c"  (in directory: /home/richard/Documents/forum)
untitled.c: In function ‘main’:
untitled.c:15:3: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
   gets(filename);
   ^~~~
   fgets
untitled.c:20:4: warning: ISO C forbids nested functions [-Wpedantic]
    int match( char *word )
    ^~~
untitled.c:35:19: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
        while ((ch=getc(fp)) != EOF) {
                   ^~~~
At top level:
untitled.c:20:8: warning: ‘match’ defined but not used [-Wunused-function]
    int match( char *word )
        ^~~~~
Compilation finished successfully.

Note: The compiler states Compilation finished successfully. However, all that means is the compiler produce a 'work around' for each of the syntax problems in the code. That does not mean the correct code was produced.

When compiling, always enable the warnings then fix those warnings.

for gcc, at a minimum use: -Wall -Wextra -Wconversion -pedantic -std=gnu11 Note: other compilers use different options to produce the same results

OT: for ease of readability and understanding: Please consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.

after correcting the compiler found problems and some of the logic problems and the formatting, here is the result:

#include <stdio.h>   // fgets(), printf(), perror()
#include <stdlib.h>  // exit(), EXIT_FAILURE
#include <string.h>  // strcmp()

int main( void )
{
    FILE *fp;
    char filename[100];

    int linecount = 0;

    printf("Enter a filename :");
    if( !fgets(filename, sizeof( filename ), stdin)  )
    {
        perror( "fgets failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fgets for file name successful

    fp = fopen(filename,"r");
    if ( !fp )
    {
        perror( "fopen for input file failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    char line[2048];  
    while ( fgets( line, sizeof( line ), fp) )
    {
        linecount++;
    }

    printf("Lines : %d \n", linecount);

    return(0);
}


int match( char *word )
{
    char *targets[] = {"auto", "the", NULL};

    for( char *t = targets[0]; t; t++ )
    {
        if( strcmp(*targets, word) == 0 )
        {
            return 1;
        }
    }

    return 0;
}

Notice that the function: match() is never called and to call match(), need code to extract a single word from the input line, perhaps via calls to strtok()

user3629249
  • 16,402
  • 1
  • 16
  • 17