This is more what I was thinking about. Though, it will suffer from the small bug that sly mentioned above.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
char buf[BUFSIZ];
char ch;
int nol = 0, not = 0, nob = 0, noc = 0, no_empty = 0;
int i;
if ( (fp = fopen("filename.cpp", "r")) == NULL )
{
printf("Could not open file for reading.\n\n");
exit(1);
}
while ( (fgets( buf, BUFSIZ, fp) != '\0') )
{
for ( i = 0; (ch = buf[i]) != '\0'; i++ )
{
if ( i == 0 && ch == '\n' )
{
nol++;
noc++;
no_empty++;
break;
}
switch ( ch )
{
case ' ':
nob++;
noc++;
break;
case '\n':
nol++;
noc++;
break;
case '\t':
not++;
noc++;
break;
default:
noc++;
}
}
}
printf("No. of chars: %d\n", noc);
printf("No. of spaces: %d\n", nob);
printf("No. of lines: %d\n", nol);
printf("No. of tabs: %d\n", not);
printf("No. of blank lines: %d\n", no_empty);
system("PAUSE");
return 0;
}