Tuesday 31 October 2017

CO4 Assignment 3rd question solution

Implement the following functions. Their meanings are given below.
a) int strCount (char *filename);
returns a count of no. of strings in a text file identified by the filename in the parameter.
b) int sentenceCount (char *filename);
returns a count of no. of sentences in the identified text file. A sentence is detected when
the last character of a word is the full stop.

Solution:


#include <stdio.h>
#include <stdlib.h>
int strCount (char *filename)
{
               FILE *fp;
               char ch;
               int wordcount=0;
               fp = fopen(filename,"r");

   // If file opened successfully, then write the string to file
               if ( fp )
               {
                              while ((ch=getc(fp)) != EOF)
                                                            if (ch == ' ' || ch == '\n') { ++wordcount; }
               }
               else
    {
               printf("Failed to open the file\n");
    }

    printf("No. of Words : %d \n", wordcount+1);
    fclose(fp);
}
int sentenceCount (char *filename)
{
               FILE *fp;
               char ch;
               int sentenceCount=0;
               fp = fopen(filename,"r");

   // If file opened successfully, then write the string to file
               if ( fp )
               {
                              while ((ch=getc(fp)) != EOF)
                                                            if (ch == '.') { ++sentenceCount; }
               }
               else
    {
               printf("Failed to open the file\n");
    }

    printf("No. Of sentences : %d \n", sentenceCount);
    fclose(fp);
              
}
int main()
{
               char filename[100];
               printf("Enter a filename :");
               gets(filename);
               strCount(filename);
               sentenceCount (filename);
}

Outputs:

No comments:

Post a Comment