Skip to content
Snippets Groups Projects
Commit 3613995c authored by Kurucz György's avatar Kurucz György
Browse files

Added support for file input. Now only matching lines are printed.

parent dfb102e4
Branches
No related tags found
No related merge requests found
Ami még hiányzik:
programozói dokumentáció
felhasználói dokumentáció
stdin bemenet
kód szépítése (főleg a main.c)
#include <stdbool.h>
#include <stdio.h>
struct regex;
typedef struct regex regex;
......@@ -6,3 +7,4 @@ typedef struct regex regex;
regex *regex_compile(char* pattern, bool debug_print);
void regex_destroy(regex *pattern);
int regex_match(regex *pattern, char *str);
int regex_match_file(regex *pattern, FILE *f);
......@@ -6,37 +6,69 @@
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc < 3) {
if (argc < 2) {
printf("No regex argument found!\n");
return 1;
}
if (argc < 3) { /* TODO */
printf("STDIN input not yet implemented!\n");
return 1;
}
char *pattern = argv[1];
char *text = argv[2];
regex *r = regex_compile(pattern, false);
if (!r) {
printf("Bad regex parse.\n");
return 1;
}
//printf("-------------\n");
char *text = NULL;
FILE *f = fopen(argv[2], "r");
int success = 0;
if (f) {
if (fseek(f, 0L, SEEK_END) == 0) {
long int size = ftell(f);
if (size > 0) {
text = malloc(sizeof(char) * (size + 1));
text[size] = '\0';
if(fseek(f, 0L, SEEK_SET) == 0) {
fread(text, sizeof(char), size, f);
if (ferror(f) == 0) {
success = 1;
}
}
}
}
fclose(f);
}
if (!success) {
free(text);
printf("Failed to read file.\n");
return 1;
}
int match;
while(*text) {
match = regex_match(r, text);
char *t;
char *last_line = text;
for (t = text; *t; t++) {
match = regex_match(r, t);
if (match != -1) {
printf("{l=%d}[", match);
break;
char *k = last_line;
int start = 0;
while (*k && *k != '\n') {
if (k == t) {
printf("\x1b[32m");
start = 1;
}
printf("%c", *text);
text++;
if (start && match-- == 0) printf("\x1b[0m");
printf("%c", *k);
k++;
}
while (*text) {
if (match-- == 0) printf("]");
printf("%c", *text);
text++;
}
if (match-- == 0) printf("]");
printf("\n");
}
if (*t == '\n') last_line = t+1;
}
regex_destroy(r);
free(text);
}
......@@ -100,13 +100,15 @@ void regex_destroy(regex *pattern) {
free(pattern);
}
int regex_match(regex *pattern, char *str){
static int _regex_match(regex *pattern, char *str, FILE *f){
dfa d = pattern->dfa;
int idx = 0;
int state = d.begin;
if (d.nodes[state].end) return 0;
int v;
char c;
while ((c = str[idx++])) {
while (v = str ? (int)str[idx] : fgetc(f), ++idx, v > 0) {
c = (char)v;
dfa_node *n = &d.nodes[state];
bool s = false;
for (int i = 0; i < n->edges; i++) {
......@@ -121,3 +123,11 @@ int regex_match(regex *pattern, char *str){
}
return -1;
}
int regex_match(regex *pattern, char *str) {
return _regex_match(pattern, str, NULL);
}
int regex_match_file(regex *pattern, FILE *f) {
return _regex_match(pattern, NULL, f);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment