Order Now

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



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

    printf("\nUnable to open file for reading.");

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

  while((c= fgetc(fp))!=EOF)
        else if (c==' ')

  words += lines;

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


  return 0;

Share this post