C++ Program to Count Characters, spaces, tabs and lines from a file

Leave a Comment
#include<iostream.h>
#include<fstream.h>
#include<conio.h>

void main()
{
FILE *fp;
//a pointer to file
char ch;
int nol=0,not=0,nos=0;nos=0;
//initializing by zero in order to avoid any garbage value
fp=fopen("test.c","r"); //open file test.c in read only mode
while(1)
{
ch=fgetc(fp);

//read each character of file in ch using pointer file pointer fp
if(ch==EOF) //if end of file in reached
break;
noc++;
//count number of characters
if(ch==' ')
//if space is read into ch increase its count
nos++;
if(ch='\n')

//if new line is read into ch increase its count
nol++;
if(ch=='\t')

//if tab is read increase its count
not++;
}

fclose(fp); //close file
printf("\n Number of Cahracters=%d",noc);
printf("\n Number of Spaces =%d",nos);
printf("\n Number of Tabs=%d",not);
printf("\n Number of Lines=%d",nol);

getche();
}

0 comments: