While Trying to count the number of lines in a text file, I noticed that fgetc is always returning EOF. This code was working on Freebsd 10 but now it's not working on Mac OSX. I checked the file to see if it was empty, it's not, it's about 1 KB in size and contains 16 lines. I added a line to seek to the beginning of the file thinking that's the problem, but it's still returning EOF. So why is fgetc always returning EOF?
int getLines(int listFd, int *lines)
{
/* Declarations */
*lines = 0;
int ch;
FILE *list;
/* Get File Stream */
list = fdopen(listFd, "r");
if(list == NULL)
{
printf("Can't Open File stream\n");
return -1;
}
/* Seek To beginning Of file */
fseek(list, 0, SEEK_SET);
/* Get Number of Lines */
while(!feof(list))
{
ch = fgetc(list);
if(ch == '\n')
{
lines++;
}
else if(ch == EOF)
{
break;
}
}
printf("lines: %d\n", *lines);
/* Clean up and Exit */
fclose(list);
return 0;
}