aboutsummaryrefslogtreecommitdiff
path: root/toys/other/tac.c
blob: 06e97205ca923389ab8dd9eae4196eb1a260c610 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* tac.c - output lines in reverse order
 *
 * Copyright 2012 Rob Landley <rob@landley.net>

USE_TAC(NEWTOY(tac, NULL, TOYFLAG_USR|TOYFLAG_BIN))

config TAC
  bool "tac"
  default y
  help
    usage: tac [FILE...]

    Output lines in reverse order.
*/

#include "toys.h"

static void do_tac(int fd, char *name)
{
  struct arg_list *list = NULL;
  FILE *fp;

  if (fd == -1) {
    perror_msg_raw(name);
    return;
  }

  // Read in lines.
  fp = xfdopen(fd, "r");
  for (;;) {
    char *line = NULL;
    size_t allocated_length;

    if (getline(&line, &allocated_length, fp) <= 0) break;

    struct arg_list *temp = xmalloc(sizeof(struct arg_list));
    temp->next = list;
    temp->arg = line;
    list = temp;
  }
  fclose(fp);

  // Play them back.
  while (list) {
    struct arg_list *temp = list->next;
    xprintf("%s", list->arg);
    free(list->arg);
    free(list);
    list = temp;
  }
}

void tac_main(void)
{
  loopfiles_rw(toys.optargs, O_RDONLY, 0, do_tac);
}