I have to divide a database and I wanted the statistics of each subdirectory that I am going to create. The database is a dictionary comprising of words and their corresponding phonemic translations. https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/cmudict/sphinxdict/cmudict_SPHINX_40 the database can be found here. I have written a program to count the number of bytes in a subdirectory say the number of bytes in A,B etc. I have not considered the special characters as I am not considering them at the moment. I don't know why my program is getting stuck in an infinite loop!?

/* program used to determine the number of characters and in turn the number of bytes in an
 alphabet entry i.e. number of bytes in 'A', 'B' etc..
 the program gets stuck in an infinite loop and I don't know why.
int main(){
FILE *fp;
{printf("Error opening file!");
}                           // File open and error checking
char ch;
ch= fgetc(fp);              
char alphabet='A';
unsigned long countal[26];  //to store the number of bytes for a particular entry (dictionary is sorted)
short i=0;
while(alphabet<='Z')     // A through Z, looping through the entire file untile eof.
unsigned long chars=0;
if(ch==alphabet)            /* if found then increment the number of bytes and check the size
{                              of a given entry */
while(ch!='\n')             // infinite loop??
char abcd='A';
printf("%c= ",abcd);
printf("%u bytes\n",countal[i]);
return 0;

For starters, if you're ever going to expect to compare ch against EOF, then you must declare ch as int. You'll notice that all of the character I/O functions work with int, and the reason for that is EOF.

Does database.txt use '\n' as end of line characters?
Does database.txt have a '\n' on the last line in the file?

i tried changing ch to int but it is yet not giving me the desired output. Infinite loop again :(

Please post a small sample of your database file.

edit: And fix the following:

if(ch==alphabet)            /* if found then increment the number of bytes and check the size
{                              of a given entry */

The opening brace is caught up in your comment. I assume you fixed it in the real code, because otherwise it wouldn't compile at all, much less create an infinite loop at runtime.

here is a small sample...you can compile my program and check if it's working properly or getting stucked at runtime. Please do give it a look. Many thanks!!

Turn anything that looks like this:


Into this:

while(ch != EOF && ch!='\n')

Thanks totally worked!! What was the problem????

If the stream is at the end of the file, fgetc() will always return EOF regardless of how many times you call it. In other words, unless you have a breaking condition that checks for EOF or ensure that end-of-file won't be reached in the loop, it will be infinite.