2 * rev implementation for busybox
4 * Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
6 * Licensed under GPLv2, see file LICENSE in this source tree.
9 //applet:IF_REV(APPLET(rev, BB_DIR_BIN, BB_SUID_DROP))
11 //kbuild:lib-$(CONFIG_REV) += rev.o
17 //config: Reverse lines of a file or files.
19 //usage:#define rev_trivial_usage
21 //usage:#define rev_full_usage "\n\n"
22 //usage: "Reverse lines of FILE"
28 #if ENABLE_UNICODE_SUPPORT
29 # define CHAR_T wchar_t
35 static void strrev(CHAR_T
*s
, int len
)
41 if (len
!= 0 && s
[len
] == '\n')
45 for (i
= 0; i
< len
; i
++, len
--) {
52 int rev_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
53 int rev_main(int argc UNUSED_PARAM
, char **argv
)
64 argv
= (char **)&bb_argv_dash
;
66 retval
= EXIT_SUCCESS
;
68 buf
= xmalloc(bufsize
);
73 fp
= fopen_or_warn_stdin(*argv
++);
75 retval
= EXIT_FAILURE
;
82 buf
[bufsize
- 1] = 1; /* not 0 */
83 if (!fgets(buf
+ pos
, bufsize
- pos
, fp
))
84 break; /* EOF/error */
85 if (buf
[bufsize
- 1] == '\0' /* fgets filled entire buffer */
86 && buf
[bufsize
- 2] != '\n' /* and did not read '\n' */
89 /* Line is too long, extend buffer */
91 bufsize
+= 64 + bufsize
/ 8;
92 buf
= xrealloc(buf
, bufsize
);
96 /* Process and print it */
97 #if ENABLE_UNICODE_SUPPORT
99 wchar_t *tmp
= xmalloc(bufsize
* sizeof(wchar_t));
100 /* Convert to wchar_t (might error out!) */
101 int len
= mbstowcs(tmp
, buf
, bufsize
);
104 /* Convert back to char */
105 wcstombs(buf
, tmp
, bufsize
);
110 strrev(buf
, strlen(buf
));
117 if (ENABLE_FEATURE_CLEAN_UP
)
120 fflush_stdout_and_exit(retval
);