1

I am reading from a file in c and printing it to screen. I am using fgets function to read line by line and separating strings in the line.

    int i;
    int j = 0;
    int ctr = 0;
    while (!feof(fp)){
            fgets(line, 256, fp);
            for(i=0;i<=(strlen(line));i++){
                    if(line[i]==' '|| line[i]=='\0'){
                            newString[ctr][j]='\0';
                            ctr++;  //for next word
                            j=0;    //for next word, init index to 0
                    }
                    else{
                            newString[ctr][j]=line[i];
                            j++;
                    }

            }
            //printf("the data line by line is: %s\n", line);

    }

    printf("\n Strings or words after split by space are :\n");
    for(i=0;i < ctr;i++)
    printf(" %s\n",newString[i]);

Here is the content of the file that I am reading from:
3
9 3 34 4 12 5 2
6 3 2 7 1
256 3 5 7 8 9 1



This is my output:
Strings or words after split by space are :
3

 9
 3
 34
 4
 12
 5
 2

 6
 3
 2
 7
 1

 256
 3
 5
 7
 8
 9
 1

 256
 3
 5
 7
 8
 9
 1

However it prints the last line twice, and I couldnt figure out why. Please tell me how to remove the extra one. Thanks in advance...

omer muhit
  • 65
  • 8
  • 3
    Please see [Why is `while ( !feof (file) )` always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) Use `while (fgets(line, 256, fp) != NULL)`. The function [`feof()`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/feof?view=vs-2017) does not do what you ( and many others) imagine. – Weather Vane Sep 18 '19 at 18:50
  • https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046476070&id=1043284351 this is very useful for this topic – omer muhit Sep 19 '19 at 21:16
  • So you probably know by now that the last line was not read twice. Without a `fseek` it can't be. The final read actually **failed** because there was no more to read, but the program is unaware of that because it does not test the return value from `fgets`. It then reports data that was still in the buffer after the previous, successful read. Now, `feof` picks up on the error you missed, and the loop terminates. `feof` returns `true` when *an attempt was made to read past the end of a file*. **Not** when you reach the end of file. This is a mistake that countless programmers have made. – Weather Vane Sep 19 '19 at 21:22

0 Answers0