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

Asked

Viewed 223 times

0

I wonder why when running the script below, the lines appear spaced, except for 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;

}
  • 1

    Because the expected output is 3,4,2,1 and not 4,3,2,1 ?

1 answer

1

First, you better make one cast for the return of malloc(), because in some compilers may not compile, my for example.
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 there is no \n It’s EOF. So it doesn’t break the line. If you want to test, enter the last line of your text file, you will see that now it will be "printing" correctly.

  • I hadn’t thought of that, thank you! by the way, I would like to put a ";" after each line, I tried sizeof(line)-1 but it always appears at the beginning, before the "-"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.