Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
int FindOutChars(char *fileName )
{
FILE *ifp;
char aCharacter;
int numOfCharacter = 0;
printf("in find out char() now\n\n");
ifp = fopen(fileName, "r");
if (ifp == NULL)
{ fprintf (stderr, "error");
exit (-1);
}
while (!EOF)
{
aCharacter = fgetc(ifp);
numOfCharacter++;
}
return numOfCharacter;
}-------------
I am writing this function to count the number of character in a file, everytying work except:the while loop, it seems that the programdoes not get into the loop at all, and i think the error is in this line:
while (!EOF)
Please help!

Right track Frank, but not quite.
You need to check the return value of fgetc(). If it's EOF, then you've reached the end of file.
The common way to do this is:
while ((aCharacter = fgetc(ifp)) != EOF)
{
numOfCharacter++;
}
That assigns the return value of fgetc() to aCharacter and then compares the value to EOF. Note that you have to have the parantheses around (aCharacter = fgetc(ifp)) or it will not work properly. If you don't use the extra set of parentheses, it will work like this:while (aCharacter = (fgetc(ifp) != EOF))
is the same as
while (aCharacter = fgetc(ifp) != EOF)
The character returned from fgetc() will be compared to EOF and the result of that compare (true or false) will be assigned to aCharacter. So your loop will run the correct number of times, but you won't have a character in aCharacter.
Also, on some systems, you'd need to change aCharacter from a 'char' to an 'int'. It's been a while so I don't remember exactly why. It has to do with how EOF is defined and as a char, aCharacter will never == EOF.
aCharacter as an 'int' will still work fine, just as if it were a char. Just think of it as a big char!

You can also do something like:
int FindOutChars(char *fileName )
{
FILE *ifp;
char aCharacter;
int numOfCharacter = 0,eofflg = 0;printf("in find out char() now\n\n");
ifp = fopen(fileName, "r");
if (ifp == NULL)
{ fprintf (stderr, "error");
exit (-1);
}while (!eofflg)
{
aCharacter = fgetc(ifp);
numOfCharacter++;
eofflg = feof(ifp);
}
return numOfCharacter;
}

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |