C program to count number of characters and lines in a file

      This program will count number of characters and lines in a file by reading each and every character of the input file. Whenever it encounters the ‘\n’ character it will increase the line count and for each character it read, the character count gets incremented. This way by the end of file it counts the total number of characters and lines in a given file.

count number of characters and lines



Source Code :

#include<stdio.h>
#include<stdlib.h>
int main() 
{ 
	FILE *fopen(), *fp; 
	int ch, nc, nlines; 
	char fname[30]; 
	nlines = 1; 
	nc = 0; 
	printf("Enter filename:"); 
	fflush(stdin); 
	scanf("%s", fname);       //Step 1
	fp = fopen(fname, "r");   //Step 2
	if(fp == NULL) 
	{ 
		printf("Cannot open the file %s for reading \n", fname); 
		exit(0); 
	} 
	ch = getc(fp); 
	while( ch != EOF)         //Step 3
	{ 
		if(ch == '\n')    //Step 3(i)
		nlines++; 
		nc++;             //Step 3(ii)
		ch = getc(fp); 
	} 
	fclose(fp); 
	if(nc != 0)           //Step 4 
	{ 
		printf("There are %d characters in %s \n", nc, fname); 
		printf("There are %d lines \n", nlines); 
	} 
	else 
		printf("File: %s is empty \n", fname); 
return 0; 
}   


edit-code-image

Sample Test cases:

1. Enter filename : 1.txt
   There are 52 characters in 1.txt
   There are 3 lines
 
2. Enter filename : 2.txt
   There are 43 characters in 1.txt
   There are 3 lines

Explanation:

Step 1 : The file name is read from the user using scanf() function.

Step 2 : The file is opened using the fopen() function in reading mode.

Step 3 : This while loop iterates from the start of the file to the end of file.

Step 3(i) : This If statement increments the line count if the character that is read is ‘\n’.

Step 3(ii): This step increments the character count for every characater that is read in the file.

Step 4 : This step prints the number of chracters and lines in a file based on the character count.

More Content: C Programming
Explore C Programs : C Programs