Why is my linecount in C not working?

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?

+4
source share
7 answers

You have a semicolon endpoint ; after your if . Then the block is always executed:

 { count++; } 
+10
source

Edit

 if (ch == '\n'); 

in

 if (ch == '\n') 
+4
source

Trailing with a comma after if : delete it. With a semicolon, the code is equivalent:

 if (ch == '\n') {} count++; 

means that count incremented by each iteration of the loop (every char in the file).

+3
source

you have a semicolon to delete after if

and for reading files it is better to use this code:

 while((fgets(blahblahblah)) != NULL) { counter++; } 
+1
source

Everything is fine except for the semicolon ( ; ), which should be removed from the line

 if (ch == '\n') 
+1
source

Beyond the question ; mentioned by others, an alternative solution can be found in this , as it explains why he is doing what he is doing.

0
source

You might want to consider the OS used to create and view this file.

Copied from PHP Echo Line Breaks :

  • '\ n' - linux / unix line break
  • '\ r' - classic line break in line [OS X uses the above unix \ n]
  • '\ r' + '\ n' is a line break in a line
0
source

Source: https://habr.com/ru/post/1444829/


All Articles