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

0

I would like to know why running the script below, 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;

}
    
asked by anonymous 09.01.2018 / 16:12

1 answer

1

First, you should do a cast for the return of malloc() , as some compilers might 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 the last line of the text file does not have a \n , but the EOF. Therefore, it does not give the line-break. If you want to test, give an enter in the last line of your text file, you will see that it will now be "printing" correctly.

    
09.01.2018 / 19:15