0

I am learning file I/O in C, and I watched a tutorial and saw this code:

#include <stdio.h>
#include <stdlib.h>

int main(){

    FILE *inp;
    
    char singleLine[100];
    inp = fopen("text2.txt", "r");
    
    while(!feof(inp)){
        fgets(singleLine, 100, inp);
        puts(singleLine);
    }

    fclose(inp);

    return 0;
}

and here is the text file I created for practive:

text2.txt

Are you ok
Hi
How are you
I am fine

I understood most codes, but when I was implementing the code myself the last line of the text file kept showing up one more time like this:

Are you ok

Hi

How are you

I am fine

I am fine

And this was not the case in the tutorial. Please explain to me what the problem is, thank you

Mattmmmmm
  • 155
  • 1
  • 6
  • 3
    That's a bad tutorial! See: [Why is "while (!feof(file))" always wrong?](https://stackoverflow.com/q/5431941/10871073) – Adrian Mole Dec 20 '20 at 18:24
  • `while(fgets(singleLine, 100, inp) != NULL) { puts(singleLine); }` but expect the output to be double-spaced. Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane Dec 20 '20 at 18:35
  • In the text file you created, removed the end-of-line at the end of "I am fine". See what happens. – chux - Reinstate Monica Dec 20 '20 at 20:30

0 Answers0