The first problem is with your code indentation. I suggest writing it as:
Code:
void capital(FILE *fp)
{
char ch;
int count = 0;
while (ch != EOF)
{
ch = fgetc(fp);
if (ch >= 'A' && ch <= 'Z')
count++;
}
printf("\nThe total number of capital letters is %d.\n", count);
printf("\n");
fclose(fp);
}
Now, since you have not given any sample data as to when it does not work, I can only guess: perhaps this is due to the fact that fgetc() returns an int, but you are storing its return value in a char. Along this line, fgetc() returns EOF when an attempt is made to read at the end of file, so on the last iteration you would well be comparing with EOF.
A far less likely reason is that the comparison ch >= 'A' && ch <= 'Z' does not work in determining uppercase characters, and theoretically it is not guaranteed to work, so you should use isupper() from <ctype.h> instead.
Consequently, you could try changing to:
Code:
int ch;
int count = 0;
while ((ch = fgetc(fp)) != EOF)
{
if (isupper(ch))
count++;
}
One last note: it may be a better idea to let the caller close the file. After all, the caller opened the file, so the caller would expect to close it.