aboutsummaryrefslogtreecommitdiff
path: root/section.c
blob: eaefcbd8fb5b5cb67b5f54cf04f64ce7bcb12f09 (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
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
  regex_t* preg;
  int reti;
  char* linebuf;
  char insection;

  if(argc != 2) {
    fprintf(stderr, "Usage: section <REGEX>\n");
    return 1;
  }

  reti = regcomp(preg, argv[1], REG_EXTENDED);
  if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    return 1;
  }

  linebuf = (char*) calloc(4096, sizeof(char));
  insection = 0;

  while (fgets(linebuf, 4096, stdin) != NULL) {
    if (insection) {
      if (linebuf[0] != ' ' && linebuf[0] != '\t') {
        insection = 0;
      } else
        fprintf(stdout, "%s", linebuf);
    } else {
      if (linebuf[0] != ' ' && linebuf[0] != '\t') {
        reti = regexec(preg, linebuf, 0, NULL, 0);
        if (!reti) {
          fprintf(stdout, "---\n%s", linebuf);
          insection = 1;
        }
      }
    }
  }

  free(linebuf);
  regfree(preg);
}