Funkcja C, która zlicza linie w pliku
Kiedy próbuję uruchomić mój program, otrzymuję złą liczbę wydrukowanych linii.
LINES: 0
To jest wyjście, chociaż mam pięć wierszy w moim pliku .txt
Oto mój program:
#include<stdio.h>
#include<stdlib.h>
int countlines(char *filename);
void main(int argc, char *argv[])
{
printf("LINES: %d\n",countlines(argv[1]));
}
int countlines(char *filename)
{
// count the number of lines in the file called filename
FILE *fp = fopen(filename,"r");
int ch=0;
int lines=0;
if (fp == NULL);
return 0;
lines++;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
lines++;
}
fclose(fp);
return lines;
}
Jestem pewien, że to prosty błąd, ale jestem nowy w programowaniu. Każda pomoc byłaby bardzo mile widziana.