Login
Order Now
Support
theprogrammingassignmenthelp

C Program That Reads A File And Reports How Many Lines, Words, And Characters Appear In It

  • 13th Feb, 2020
  • 16:57 PM

C Programming Assignment Question

Write a C program that reads a file and reports how many lines, words, and characters appear in it.  For the purpose of this program, a word consists of a consecutive sequence of any characters except white space characters. For example, if the file lear.txt contains the following passage from King Lear,

Poor naked wretches, wheresoe’er you are,
That bide the pelting of this pitiless storm,
How shall your houseless haeds and unfed sides,
Your loop’d and window’d raggedness, defend you  
From seasons such as these? O, I have ta’en
Too little care of this!

Your program should be able to generate the following sample run:

File: lear.txt
Lines:  6
Words: 43
Chars: 210
 

C Programming Assignment Solution

 

#include
#include

int main(void) 
{
  FILE* fp = fopen("lear.txt","r");

  if(!fp)
  {
    printf("\nUnable to open file for reading.");
    exit(0);
  }

  char c;
  int lines=0,words=0,chars=0;

  while((c= fgetc(fp))!=EOF)
    {
      if(c=='\n')
          ++lines;
        else if (c==' ')
      ++words;
    else
      ++chars;
    }

  ++lines;
  words += lines;

  printf("Lines = %d\nWords = %d\nCharacters = %d",lines, words,chars);

    fclose(fp);

  return 0;
}

Share this post