I think the OP wanted to ignore blank lines. Then a readline() function is
better.
This is the full function. You can write it far more tersely, but
generally it's better to break things down and make them clear.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int blankstr(const char *str);
int fcountlines(FILE *fp);
int countlines(char *filename);
/*
is a string empty or composed entirely of blanks?
Params: str - the string
Returns: 1 if balnk, else 0
*/
int blankstr(const char *str)
{
while(*str)
{
if(!isspace( (unsigned) *str) )
return 0;
str++;
}
return 1;
}
/*
count the remaining lines in an open file
Params: fp - pointer to file
Returns: number of non-blank lines, -1 on read error
*/
int fcountlines(FILE *fp)
{
char buff[1024];
int graphflag = 0;
int answer = 0;
while(fgets(buff, 1024, fp))
{
if(!strchr(buff, '\n'))
{
if(!blankstr(buff))
graphflag = 1;
continue;
}
if(!blankstr(buff) || graphflag)
answer++;
graphflag = 0;
}
if(ferror(fp))
return -1;
return answer;
}
/*
count the non-blank lines in a file
Params: filename - path to file
Returns: number of non-blank lines
*/
int countlines(char *filename)
{
FILE *fp;
int answer;
fp = fopen(filename, "r");
if(!fp)
return -1;
answer = fcountlines(fp);
fclose(fp);
return answer;
}
#include <stdlib.h>
int main(int argc, char **argv)
{
int Nlines;
Nlines = countlines(argv[1]);
if(Nlines < 0)
{
fprintf(stderr, "Error opening or reading file\n");
exit(EXIT_FAILURE);
}
printf("%d non-blank lines\n", Nlines);
return 0;
}