Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <regex.h>
- #define LEN 100
- int getstr(char **s, FILE *f);
- int maxl = LEN;
- typedef struct a{
- char* time;
- char* hostname;
- char* app;
- char* message;
- } info;
- int main(){
- const char pattern[] = "[a-zA-Z0-9_-]+ [0-9][0-9] ([0-9][0-9]:[0-9][0-9]:[0-9][0-9]) ([a-zA-Z0-9_-]+) ([a-zA-Z0-9_-]+)(\\[[0-9]+\\])?: (.+)";
- regex_t expr_compiled;
- regcomp(&expr_compiled, pattern, REG_EXTENDED);
- regmatch_t groups[6];
- char* string = (char*)calloc(maxl, sizeof(char));
- info* l = (info*)calloc(1, sizeof(info));
- unsigned int len = 0;
- FILE *in;
- char name[] = "input.txt";
- in = fopen(name, "r");
- while(getstr(&string, in)){
- if (regexec(&expr_compiled, (const char *)string, 6, groups, 0) == 0){
- len++;
- l = (info*)realloc(l, sizeof(struct a) * (len+1));
- l[len].time = (char*)calloc(groups[1].rm_eo - groups[1].rm_so + 10, sizeof(char));
- strncpy(l[len].time, &(string[groups[1].rm_so]), groups[1].rm_eo - groups[1].rm_so);
- l[len].hostname = (char*)calloc(groups[2].rm_eo - groups[2].rm_so + 10, sizeof(char));
- strncpy(l[len].hostname, &(string[groups[2].rm_so]), groups[2].rm_eo - groups[2].rm_so);
- l[len].app = (char*)calloc(groups[3].rm_eo - groups[3].rm_so + 10, sizeof(char));
- strncpy(l[len].app, &(string[groups[3].rm_so]), groups[3].rm_eo - groups[3].rm_so);
- l[len].message = (char*)calloc(groups[5].rm_eo - groups[5].rm_so + 10, sizeof(char));
- strncpy(l[len].message, &(string[groups[5].rm_so]), groups[5].rm_eo - groups[5].rm_so);
- }
- }
- for(int i = 1; i <= len; i++){
- printf("Msg #%d\n", i);
- printf(" time:\t%s\n", l[i].time);
- printf(" host:\t%s\n", l[i].hostname);
- printf(" app:\t%s\n", l[i].app);
- printf(" msg:\t%s\n", l[i].message);
- }
- fclose(in);
- free(l);
- free(string);
- regfree(&expr_compiled);
- return 0;
- }
- int getstr(char **s, FILE *f)
- {
- int i=0;
- char c;
- memset((*s), '\0', sizeof(char)*maxl);
- while(((c = fgetc(f)) != EOF) && (c != '\n')){
- (*s)[i++] = c;
- if(i>=maxl-1){
- maxl += LEN;
- (*s) = (char*)realloc((*s), sizeof(char) * maxl);
- }
- }
- return c != EOF;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement