summaryrefslogtreecommitdiff
path: root/util/sbase/rev.c
blob: 9ac1da659f16139617850488b0691c2e06970530 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "text.h"
#include "util.h"

static void
usage(void)
{
	eprintf("usage: %s [file ...]\n", argv0);
}

static void
rev(FILE *fp)
{
	static char *line = NULL;
	static size_t size = 0;
	size_t i;
	ssize_t n;
	int lf;

	while ((n = getline(&line, &size, fp)) > 0) {
		lf = n && line[n - 1] == '\n';
		i = n -= lf;
		for (n = 0; i--;) {
			if (UTF8_POINT(line[i])) {
				n++;
			} else {
				fwrite(line + i, 1, n + 1, stdout);
				n = 0;
			}
		}
		if (n)
			fwrite(line, 1, n, stdout);
		if (lf)
			fputc('\n', stdout);
	}
}

int
main(int argc, char *argv[])
{
	FILE *fp;
	int ret = 0;

	ARGBEGIN {
	default:
		usage();
	} ARGEND

	if (!argc) {
		rev(stdin);
	} else {
		for (; *argv; argc--, argv++) {
			if (!strcmp(*argv, "-")) {
				*argv = "<stdin>";
				fp = stdin;
			} else if (!(fp = fopen(*argv, "r"))) {
				weprintf("fopen %s:", *argv);
				ret = 1;
				continue;
			}
			rev(fp);
			if (fp != stdin && fshut(fp, *argv))
				ret = 1;
		}
	}

	ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>");

	return ret;
}