C program to count characters, words and lines in a text file

Write a programme to count range of characters, words and contours during a document. Logic to count characters, words and contours during a get in programme. a way to count total characters, words and contours during a document in C programming.

C program to count characters, words and lines in a text file
Count Character In File

EXAMPLE:- 

Source file:-
Welcome to cprogrammingsimply.in
You are working with file system

Output:-
Total characters = 65
Total words      = 9
Total lines      = 2

ALGORITHM:-

1. Open source file in r (read) mode.
2. Initialize three variables characters = 0, words = 0 and lines = 0 to store counts.
3. Read a character from file and store it to some variable say ch.
4. Increment characters count.
Increment words count if current character is whitespace character i.e. if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0').
Increment lines count if current character is new line character i.e. if (ch == '\n' || ch == '\0').
5. Repeat step 3-4 till file has reached end.
6. Finally after file has reached end increment words and lines count by one if total characters > 0 to make sure you count last word and line.

PROGRAM CODE:-

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

int main() {
	FILE * file;
	char path[100];

	char ch;
	int num_of_characters, num_of_words, num_of_lines;


	/* Input path of files to merge to third file */
	printf("Enter source file path: ");
	scanf("%s", path);

	/* Open source files in 'r' mode */
	file = fopen(path, "r");


	/* Check if file opened successfully */
	if (file == NULL)
	{
		printf("\nUnable to open file.\n");
		printf("Please check if file exists and you have read privilege.\n");

		exit(EXIT_FAILURE);
	}

	/*
	 * Logic to count num_of_characters, num_of_words and num_of_lines.
	 */
	num_of_characters = num_of_words = num_of_lines = 0;
	while ((ch = fgetc(file)) != EOF)
	{
		num_of_characters++;

		/* Check new line */
		if (ch == '\n' || ch == '\0')
			num_of_lines++;

		/* Check num_of_words */
		if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
			num_of_words++;
	}

	/* Increment num_of_words and num_of_lines for last word */
	if (num_of_characters > 0)
	{
		num_of_words++;
		num_of_lines++;
	}

	/* Print file statistics */
	printf("\n");
	printf("Total num_of_characters = %d\n", num_of_characters);
	printf("Total num_of_words      = %d\n", num_of_words);
	printf("Total num_of_lines      = %d\n", num_of_lines);


	/* Close files to release resources */
	fclose(file);

	return 0;
}

OUTPUT:-

Enter source file path: mydrive\file.txt

Total num_of_characters = 65
Total num_of_words      = 9
Total num_of_lines      = 2