I am trying to read a text file, but before that I want to know how many elements I will read. Therefore, I need to count the lines of a text file. So far I have this:
int getLinecount (char *file) { int ch, count = 0; FILE *fp = fopen(file, "r"); if(fp == NULL) { return -1; } while((ch = fgetc(fp)) != EOF) { if (ch == '\n'); { count++; } } fclose(fp); return count; }
It worked very well. I have not changed anything in the text file, and yet it prints 130,000, although the file has only 10,000 lines. The only thing I wrote in my main:
linecount = getLinecount("...");
I'm really curious where the mistake is. Also, is there a better way to get linecount?
source share