Search code examples
cfeof

Counting lines in a data file


In this code snippet I try to count the number of rows contained in a file. The data are divided into seven columns and 421 rows. However, the total number outmput returns as 422, that is counted in more than one line. Why? How can I avoid this problem?

I know it's wrong to use instruction while (! Feof (inStr)), but I was asked explicitly to use it.

int valid = 0;

[...]

while(!feof(inStr)){
        fscanf(inStr," %c %f %f %f %f %f %d",&app1, &app2, &app3, &app4, &app5, &app6,&app7);
        valid++;
    }
    printf("%d",valid);

Solution

  • The problem is that you need to do the feof check immediately after you try to fscanf, but before you increment your row counter. Otherwise you will increment it for the eof.

    while(1){
        fscanf(inStr," %c %f %f %f %f %f %d",&app1, &app2, &app3, &app4, &app5, &app6,&app7);
        if (feof(inStr)) break;
        valid++;
    }
    printf("%d",valid);
    

    Of course, you could also do as Martin James suggested and subtract one from the result.