In: Computer Science
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
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
/* Input path of file*/
printf("Enter source file path: ");
scanf("%s", path);
/* Open source files in read mode */
file = fopen(path, "r");
/* Check if the file has opened successfully */
if (file == NULL)
{
printf("\nUnable to open the file.\n");
printf("Please check if file exists\n");
exit(EXIT_FAILURE);
}
//Logic to count characters, words and lines.
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check new line */
if (ch == '\n' || ch == '\0')
lines++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;
lines++;
}
/* Print desired output */
printf("\n");
printf("file: %s\n", path);
printf("Characters: %d\n", characters);
printf("Words: %d\n", words);
printf("Lines: %d\n", lines);
/* Close the file*/
fclose(file);
return 0;
}