C program that reads a text file and prints lines in reverse order

I would like to know why when running the script below, the lines appear spaced, except the first line.

Input

Linha1
Linha2
Linha3
Linha4

Expected output

Produtos:
- Linha3
- Linha4
- Linha2
- Linha1

Output obtained

Produtos:
- Linha1-Linha 2
- Linha3
- Linha4

Code

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

typedef struct linha {
  char *produtos;
  struct linha *prev;
} linha;

FILE *file;   
int main() {

  linha *tail = NULL;
  file = fopen("text.txt","r");
  char linha1[255];

  while (fgets(linha1,255,file)!=NULL) {
    linha *l1 = malloc(sizeof(linha));
    l1->produtos = malloc(strlen(linha1)+1);
    strcpy(l1->produtos,linha1);
    l1->prev = tail;
    tail = l1;
  }

  linha *current;
  current = tail;
    printf("Produtos:\n");
  while (current != NULL) {
    printf("- %s",current->produtos);
    current = current->prev;
  }
  return 0;

}
Author: Jefferson Quesado, 2018-01-09

1 answers

First, it's good to make a cast for the return of malloc(), as in some compilers it may not compile, mine for example.
It would look like this:

linha *l1 =(linha*) malloc(sizeof(linha));
l1->produtos =(char*) malloc(strlen(linha1)+1);

I will consider that the expected output is

Produtos:  
- Linha4  
- Linha3  
- Linha2  
- Linha1  

This happens because in the last line of the text file does not have a \n and rather the EOF. So he doesn't give the line break. If you want to test, enter the last line of your text file, you will see that it will now be "printing" from correct way.

 1
Author: game doido, 2018-01-09 19:19:34