summaryrefslogtreecommitdiff
path: root/cb.c
blob: 602f5f61b99e85f297f2f39415e2951925832c37 (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
75
76
77
#define _XOPEN_SOURCE 700
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static void output(int level, char *buf)
{
	while (level-- > 0) {
		putchar('\t');
	}
	while (isblank(*buf)) {
		buf++;
	}
	puts(buf);
}

static int cb(const char *path)
{
	FILE *in = stdin;
	if (path && strcmp(path, "-") != 0) {
		in = fopen(path, "r");
	}

	if (in == NULL) {
		fprintf(stderr, "cb: %s: %s\n", path, strerror(errno));
		return 1;
	}

	int c;
	char buf[LINE_MAX] = {0};
	size_t pos = 0;
	int level = 0;

	while ((c = fgetc(in)) != EOF) {
		buf[pos++] = c;
		if (c == '{' || c == ';' || c == '}') {
			output(level, buf);
			memset(buf, '\0', sizeof(buf));
			pos = 0;
			if (c == '{') {
				level++;
			}
			if (c == '}') {
				level--;
			}
		}
	}

	if (in != stdin) {
		fclose(in);
	}

	return 0;
}

int main(int argc, char *argv[])
{
	setlocale(LC_ALL, "");

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

	int r = 0;
	do {
		r |= cb(argv[optind++]);
	} while (optind < argc);
	return r;
}