Counting number of lines in the file in C
11,751
Solution 1
fgets()
reads till newline character or till the buffer is full
char buf[200];
while(fgets(buf,sizeof(buf),fileHandle) != NULL)
{
count++;
}
fgetc()
is an issue here because you encounter EOF
first and exit your do while
loop and never encounter a \n
character so count remains untouched for the last line in your file.If it happens to be there is a single line in your file that the count
will be 0
Solution 2
Here is another option (other than keeping track of last character before EOF).
int ch;
int charsOnCurrentLine = 0;
while ((ch = fgetc(fileHandle)) != EOF) {
if (ch == '\n') {
count++;
charsOnCurrentLine = 0;
} else {
charsOnCurrentLine++;
}
}
if (charsOnCurrentLine > 0) {
count++;
}
Author by
caddy-caddy
Updated on June 18, 2022Comments
-
caddy-caddy about 2 years
I'm writing a function that reads the number of lines in the given line. Some text files may not end with a newline character.
int line_count(const char *filename) { int ch = 0; int count = 0; FILE *fileHandle; if ((fileHandle = fopen(filename, "r")) == NULL) { return -1; } do { ch = fgetc(fileHandle); if ( ch == '\n') count++; } while (ch != EOF); fclose(fileHandle); return count; }
Now the function doesn't count the number of lines correctly, but I can't figure out where the problem is. I would be really grateful for your help.
-
Karoly Horvath about 9 years" doesn't count the number of lines correctly" - elaborate....
-
caddy-caddy about 9 yearswhen there is a file with 1 line it, the function returns 0.
-
pens-fan-69 about 9 yearsIf it's simply that you are off by 1 when there is no trailing newline, you will need to keep track of what the previous character is (e.g. the character before the EOF) and add 1 if it is not a newline.
-
-
Karoly Horvath about 9 yearswhat if there are two lines, not one?
-
Gopi about 9 years@KarolyHorvath Again we see the same issue !! That's the reason I suggested fgets()