blob: ddadcc7bc6d2368c08de47be42a8753ab1fc8596 [file] [log] [blame]
Denis Vlasenko482f2b32008-01-07 16:14:14 +00001/* vi: set sw=4 ts=4: */
2/*
3 * tac implementation for busybox
4 *
5 * Copyright (C) 2003 Yang Xiaopeng <yxp at hanwang.com.cn>
6 * Copyright (C) 2007 Natanael Copa <natanael.copa@gmail.com>
7 * Copyright (C) 2007 Tito Ragusa <farmatito@tiscali.it>
8 *
9 * Licensed under GPLv2, see file License in this tarball for details.
10 *
11 */
12
13/* tac - concatenate and print files in reverse */
14
15/* Based on Yang Xiaopeng's (yxp at hanwang.com.cn) patch
16 * http://www.uclibc.org/lists/busybox/2003-July/008813.html
17 */
18
19#include "libbb.h"
20
21/* This is a NOEXEC applet. Be very careful! */
22
Denis Vlasenkode24bd92008-01-09 23:00:00 +000023struct lstring {
24 int size;
25 char buf[];
26};
27
Denis Vlasenko482f2b32008-01-07 16:14:14 +000028int tac_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenko68404f12008-03-17 09:00:54 +000029int tac_main(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenko482f2b32008-01-07 16:14:14 +000030{
31 char **name;
32 FILE *f;
Denis Vlasenkode24bd92008-01-09 23:00:00 +000033 struct lstring *line = NULL;
Denis Vlasenko482f2b32008-01-07 16:14:14 +000034 llist_t *list = NULL;
35 int retval = EXIT_SUCCESS;
Denis Vlasenko474d1c52008-01-07 19:06:47 +000036
Denis Vlasenko482f2b32008-01-07 16:14:14 +000037 argv++;
38 if (!*argv)
39 *--argv = (char *)"-";
40 /* We will read from last file to first */
41 name = argv;
42 while (*name)
43 name++;
44
45 do {
Denis Vlasenkode24bd92008-01-09 23:00:00 +000046 int ch, i;
47
Denis Vlasenko482f2b32008-01-07 16:14:14 +000048 name--;
49 f = fopen_or_warn_stdin(*name);
50 if (f == NULL) {
51 retval = EXIT_FAILURE;
52 continue;
53 }
54
Denis Vlasenkode24bd92008-01-09 23:00:00 +000055 errno = i = 0;
56 do {
57 ch = fgetc(f);
58 if (ch != EOF) {
59 if (!(i & 0x7f))
60 /* Grow on every 128th char */
61 line = xrealloc(line, i + 0x7f + sizeof(int) + 1);
62 line->buf[i++] = ch;
63 }
64 if ((ch == '\n' || ch == EOF) && i) {
65 line = xrealloc(line, i + sizeof(int));
66 line->size = i;
67 llist_add_to(&list, line);
68 line = NULL;
69 i = 0;
70 }
71 } while (ch != EOF);
72 /* fgetc sets errno to ENOENT on EOF, but */
73 /* fopen_or_warn_stdin would catch this error */
74 /* so we can filter it out here. */
Denis Vlasenko482f2b32008-01-07 16:14:14 +000075 if (errno && errno != ENOENT) {
76 bb_simple_perror_msg(*name);
77 retval = EXIT_FAILURE;
78 }
79 } while (name != argv);
80
81 while (list) {
Denis Vlasenkode24bd92008-01-09 23:00:00 +000082 line = (struct lstring *)list->data;
83 xwrite(STDOUT_FILENO, line->buf, line->size);
84 if (ENABLE_FEATURE_CLEAN_UP) {
85 free(llist_pop(&list));
86 } else {
87 list = list->link;
88 }
Denis Vlasenko482f2b32008-01-07 16:14:14 +000089 }
Denis Vlasenko474d1c52008-01-07 19:06:47 +000090
Denis Vlasenko482f2b32008-01-07 16:14:14 +000091 return retval;
92}