sbase/grep.c

113 lines
1.9 KiB
C
Raw Normal View History

2011-05-22 21:36:34 -04:00
/* See LICENSE file for copyright and license details. */
#include <regex.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2011-05-23 20:13:34 -04:00
#include <unistd.h>
2011-05-25 15:40:47 -04:00
#include "text.h"
2011-06-18 01:42:24 -04:00
#include "util.h"
enum { Match = 0, NoMatch = 1, Error = 2 };
2011-05-22 21:36:34 -04:00
static void grep(FILE *, const char *, regex_t *);
2012-05-31 14:38:25 -04:00
static void usage(void);
2011-05-22 21:36:34 -04:00
static bool vflag = false;
static bool many;
static bool match = false;
static char mode = 0;
int
main(int argc, char *argv[])
{
2012-05-31 14:38:25 -04:00
int i, n, flags = REG_NOSUB;
2011-05-22 21:36:34 -04:00
regex_t preg;
FILE *fp;
2012-05-31 14:38:25 -04:00
ARGBEGIN {
case 'E':
flags |= REG_EXTENDED;
break;
case 'c':
case 'l':
case 'n':
case 'q':
2012-06-09 13:49:02 -04:00
mode = ARGC();
2012-05-31 14:38:25 -04:00
break;
case 'i':
flags |= REG_ICASE;
break;
case 'v':
vflag = true;
break;
default:
usage();
} ARGEND;
2011-05-22 21:36:34 -04:00
2012-05-31 14:38:25 -04:00
if(argc == 0)
usage(); /* no pattern */
if((n = regcomp(&preg, argv[0], flags)) != 0) {
2012-05-12 12:54:36 -04:00
char buf[BUFSIZ];
regerror(n, &preg, buf, sizeof buf);
2012-05-12 13:01:27 -04:00
enprintf(Error, "invalid pattern: %s\n", buf);
2012-05-12 12:54:36 -04:00
}
2012-05-31 14:38:25 -04:00
many = (argc > 1);
if(argc == 1)
2011-05-22 21:36:34 -04:00
grep(stdin, "<stdin>", &preg);
2012-05-31 14:38:25 -04:00
else for(i = 1; i < argc; i++) {
if(!(fp = fopen(argv[i], "r")))
enprintf(Error, "fopen %s:", argv[i]);
grep(fp, argv[i], &preg);
2011-05-22 21:36:34 -04:00
fclose(fp);
}
2011-06-18 01:42:24 -04:00
return match ? Match : NoMatch;
2011-05-22 21:36:34 -04:00
}
void
grep(FILE *fp, const char *str, regex_t *preg)
{
2011-05-25 15:40:47 -04:00
char *buf = NULL;
long n, c = 0;
size_t size = 0, len;
2011-05-22 21:36:34 -04:00
2011-05-25 15:40:47 -04:00
for(n = 1; afgets(&buf, &size, fp); n++) {
if(buf[(len = strlen(buf))-1] == '\n')
buf[--len] = '\0';
2011-05-22 21:36:34 -04:00
if(regexec(preg, buf, 0, NULL, 0) ^ vflag)
continue;
2011-05-25 15:40:47 -04:00
switch(mode) {
case 'c':
2011-05-22 21:36:34 -04:00
c++;
break;
2011-05-25 15:40:47 -04:00
case 'l':
puts(str);
goto end;
case 'q':
2011-06-18 01:42:24 -04:00
exit(Match);
2011-05-25 15:40:47 -04:00
default:
2011-05-22 21:36:34 -04:00
if(many)
printf("%s:", str);
if(mode == 'n')
2011-05-25 15:40:47 -04:00
printf("%ld:", n);
printf("%s\n", buf);
2011-05-25 15:40:47 -04:00
break;
2011-05-22 21:36:34 -04:00
}
match = true;
}
if(mode == 'c')
2011-05-25 15:40:47 -04:00
printf("%ld\n", c);
end:
2011-06-18 01:42:24 -04:00
if(ferror(fp))
enprintf(Error, "%s: read error:", str);
2011-05-25 15:40:47 -04:00
free(buf);
2011-05-22 21:36:34 -04:00
}
2012-05-31 14:38:25 -04:00
void
usage(void)
{
enprintf(Error, "usage: %s [-Ecilnqv] pattern [files...]\n", argv0);
}