-
Notifications
You must be signed in to change notification settings - Fork 39
/
slice.c
72 lines (62 loc) · 1.49 KB
/
slice.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
/*
slice - Prints matched substrings (with line length limitation)
Copyright (c) 2017 Minero Aoki
This program is free software.
Redistribution and use in source and binary forms,
with or without modification, are permitted.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
static void do_slice(regex_t *pat, FILE *f);
int
main(int argc, char *argv[])
{
regex_t pat;
int err;
int i;
if (argc < 2) {
fputs("no pattern\n", stderr);
exit(1);
}
err = regcomp(&pat, argv[1], REG_EXTENDED | REG_NEWLINE);
if (err != 0) {
char buf[1024];
regerror(err, &pat, buf, sizeof buf);
puts(buf);
exit(1);
}
if (argc == 2) {
do_slice(&pat, stdin);
}
else {
for (i = 2; i < argc; i++) {
FILE *f;
f = fopen(argv[i], "r");
if (!f) {
perror(argv[i]);
exit(1);
}
do_slice(&pat, f);
fclose(f);
}
}
regfree(&pat);
exit(0);
}
static void
do_slice(regex_t *pat, FILE *src)
{
char buf[4096];
while (fgets(buf, sizeof buf, src)) {
regmatch_t matched[1];
if (regexec(pat, buf, 1, matched, 0) == 0) {
char *str = buf + matched[0].rm_so;
regoff_t len = matched[0].rm_eo - matched[0].rm_so;
fwrite(str, len, 1, stdout);
fputc('\n', stdout);
}
}
}