-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
107 lines (88 loc) · 2.18 KB
/
main.c
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* trex (pronounced t-rex) is a simple command line utility that works
* similar to 'grep'. The main difference is that it only shows the matching
* groups of a regular expressions.
*
* This allows simple parsing out of values from text with some context.
*
* This utility uses the UNIX/POSIX regex.h implementation of pattern matcher,
* therefore POSIX syntax applies for provided patterns.
*
* TODO:
* - allow input of multiple files
* - add -i flag for case insensitive matches (eflags)
* - add -0 flag for \0 separated matches instead of ' '
*
* authors:
* - Thomas Richner <mail@trichner.ch>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"
#include "lr.h"
#include "matcher.h"
//#include "ftree_matcher.h"
int main(int argc, char **argv) {
char** path_list = xmalloc(2*sizeof(char*));
path_list[0] = "/home/trichner/tdot";
if (argc <= 1) {
panic("No pattern provided.\nUsage: trex <pattern> [file]");
}
/* allocate memory for capture groups */
matcher_t *matcher = matcher_new();
matcher_make(matcher, argv[1], 0);
if(argc >= 3 && strcmp(argv[2],"-")!= 0){
match_file(argv[2], matcher);
}else{
match_file(NULL, matcher);
}
matcher_free(matcher);
free(matcher);
return 0;
}
int match_file(const char* path, matcher_t* matcher){
line_reader_t *lr = lr_new();
FILE *f;
size_t len;
char *line;
if (path) {
f = fopen(path, "r");
if (f == NULL) {
panic("Cannot open file.");
}
} else {
f = stdin;
}
/* read file line-by-line */
lr_init(lr, f);
while ((line = lr_next(lr, &len))) {
/* exec regex */
matcher_match_line(matcher, line, len, 0);
/* print matches */
int nmatches = 0;
match_t *match;
int i = 0;
while ((match = matcher_match_get(matcher, i))) {
if (match->start) {
if (nmatches) {
printf(" ");
}
printf("%.*s", match->len, match->start);
nmatches++;
}
i++;
}
if (nmatches) {
printf("\n");
}
/* reset, make ready for next matching */
matcher_match_reset(matcher);
}
if (!feof(f)) {
panic("Input error.");
}
/* cleanup */
lr_free(lr);
free(lr);
}