summaryrefslogtreecommitdiff
path: root/plaintext.c
blob: a107317a5ae876937d66658facf6f99dca543a96 (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
#define _POSIX_C_SOURCE 2
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static int plaintext(const char *path)
{
	FILE *f = stdin;
	if (path && strcmp(path, "-") != 0) {
		f = fopen(path, "rb");
		if (f == NULL) {
			perror(path);
			return 1;
		}
	}

	int c = 0;
	while ((c = fgetc(f)) != EOF) {
		if (c == '\033') {
			c = fgetc(f);	/* read '[' */
			c = '\033';
			while (c != EOF && ! (0x40 <= c && c <= 0x7e)) {
				c = fgetc(f);
			}
			continue;
		}
		if (iscntrl(c) && !isspace(c)) {
			continue;
		}
		putchar(c);
	}

	if (f != stdin) {
		fclose(f);
	}
	return 0;
}

int main(int argc, char *argv[])
{
	int c;
	while ((c = getopt(argc, argv, "")) != -1) {
		switch (c) {
		default:
			return 1;
		}
	}

	if (optind >= argc) {
		return plaintext(NULL);
	}

	int r = 0;
	for (int i = optind; i < argc; i++) {
		r |= plaintext(argv[i]);
	}
	return r;
}