Friday, November 4, 2011

Counting Characters, Tabs, Spaces in C programming

Having understood the first file I/O program in detail let us now try our hand at one more. Let us write a program that will read a file and count how many characters, spaces, tabs and newlines are present in it. Here is the program…/* Count chars, spaces, tabs and newlines in a file */

# include "stdio.h"
main( )
{
FILE *fp ;
char ch ;
int nol = 0, not = 0, nob = 0, noc = 0 ;
fp = fopen ( "PR1.C", "r" ) ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
noc++ ;
if ( ch == ' ' )
nob++ ;
if ( ch == '\n' )
nol++ ;
if ( ch == '\t' )
not++ ;
}
fclose ( fp ) ;
printf ( "\nNumber of characters = %d", noc ) ;
printf ( "\nNumber of blanks = %d", nob ) ;
printf ( "\nNumber of tabs = %d", not ) ;
printf ( "\nNumber of lines = %d", nol ) ;
}424 Let Us C

Here is a sample run...

Number of characters = 125
Number of blanks = 25
Number of tabs = 13
Number of lines = 22
The above statistics are true for a file “PR1.C”, which I had on my disk. You may give any other filename and obtain different results. I believe the

No comments:

Post a Comment