Search code examples
cfilereverselines

C Reverse lines order from files


I have been asked to make a program that reverses the line order of files as input. Example:

$ cat file1 january february march

$ cat file2 one two three

$ ./program file1 file2 three two one march february january

So, I have made almost everything and the reversing works fine, but here comes the problem. The program prints the first file introduced reversed, instead of first the last file. Example:

$ ./program file1 file2 march february january three two one

I pretty tried everything but still can't figure out what's the problem. Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include "auxiliar.h"

#define MAXLINEA 2048
#define Bocabajo "bocabajo"

void Ayuda(void){
   fprintf(stdout, "%s: Uso: %s [ fichero... ]\n", Bocabajo, Bocabajo);
   fprintf(stdout, "%s: Invierte el orden de las lineas de los ficheros     (o de la entrada).\n", Bocabajo);
   exit(EX_OK);
}

int main ( int argc, char *argv[] )
{
  char linea[MAXLINEA];
  char **lineas;
  int tamanio = 0;
  int nleidos = 0;
  int i,j;
  FILE *file;

  if (argc == 2 && !strcmp(argv[1], "-h")){
    Ayuda();
  }
  else if (argc == 1) {
    tamanio = 2;
    lineas = malloc(sizeof(char *));

    while (fgets (linea, MAXLINEA, stdin) ) {
      if (nleidos >= tamanio) {
        tamanio *= 2;
        lineas = realloc (lineas, sizeof(char *) * tamanio);
        if (!lineas)
          Error(EX_OSERR, " Ubicacion memoria dinamica desconocida");
      }
      lineas[nleidos] = strdup(linea);
      nleidos++;
    }
    for ( i=0; i<nleidos; i++)
      printf ("%s", lineas[nleidos-i-1]);

    for ( i=0; i<nleidos; i++)
      free (lineas[i]);
    free (lineas);

 }else{
    for (i=1; i<argc; i++){
      tamanio = 2;
      lineas = malloc(sizeof (char *));
      nleidos = 0;
      if ((file = fopen(argv[i], "r")) == NULL){
        Error(EX_NOINPUT,".*\"%s\" ilegible o inexistente",argv[i]);
     }else{
        while (fgets (linea, MAXLINEA, file) != NULL){
          if (nleidos >= tamanio) {
            tamanio *= 2;
            lineas = realloc (lineas, sizeof(char *) * tamanio);
            if (!lineas)
              Error(EX_OSERR, " Ubicacion memoria dinamica desconcida");
          }
          lineas[nleidos] = strdup(linea);
          nleidos++;
        }
        fclose(file);

        for (j=0; j<nleidos; j++)
          printf ("%s", lineas[nleidos-j-1]);

        for (j=0; j<nleidos; j++)
          free (lineas[j]);
        free(lineas);
      }
    }
  }
  return(EX_OK);
}

PD: Sorry for my not so great english.


Solution

  • Iterate the command-line argument in the opposite direction. Change this:

    for (i=1; i<argc; i++){
    

    to this:

    for (i=argc-1; i>0; i--){