The code below works perfectly fine with
test.txt:
blah1 44.3
blah2 34.3
as soon as i add2 blank lines to the end of the text file
else kicks in:
Number of lines: 1
Number of lines: 2
line cannot be printed
Is it possible, once the end of the file is reached to exit somehow and ignore how many blank lines there are at the end?
[code]
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char name[25];
char buff[BUFSIZ];
float num;
int nooflines = 0;
if((fp=fopen("test.txt","r"))==NULL)
{
perror("File cannot be opened");
exit(1);
}
while(fgets(buff,sizeof(buff),fp)!=NULL) // read a single line from the file till i get EOF
{
if(sscanf(buff,"%s %f",name,&num)==2) // getting the name and the number from the buffer which was read from the file
{
nooflines++;
printf("%s %d", "\n Number of lines: ", nooflines);
}
else
{
printf("\nline cannot be printed\n");
exit(0);
}
}
return 0;
}
I've tried modifying the if statement to:
it worksCode:if(sscanf(buff,"%s %f",name,&num) == 2 || sscanf(buff,"%s %f",name,&num) != '\n' )
but if i add crap to the
text file:
blah1 44.3
dsds
blah2 34.3
it still reads it as a valid line (i.e. the second line in the text file is not valid it has no valid number). I tried changing the || to && but it gives me the same original problem i had.