BeniMoore BeniMoore - 1 month ago 7
C Question

Why is my regex function only running the first time around?

I'm working on some code for a homework assignment which is to search a text file for certain patterns and generate reports. Currently to test it I'm just printing my reports to the screen. But my search function only seems to be running the first time. I've tested the regex individually and they do all pull the correct matches but once I put it inside the function it only works the first time it's run. Could anyone explain to me why this is happening?

#include <stdio.h>
#include <stdlib.h>
#include <regex.h>


// Report expressions
char *reports[5] = {"^ {0,}[0-9]{1,4}", "S", "L", "S {0,1}(1|2)", "^ {0,}[0-9]{1,4} {1,} L | 3$"};

void search(FILE *fp, char *report, int index) {
regex_t reg;
char buf[256];
int reti = regcomp(&reg,report,REG_EXTENDED);

if(reti) {
printf("Regex compilation failed, noob\n");
exit(1);
}
printf("Report %d\n", index);

while(fgets(buf,sizeof(buf),fp) != NULL) {
//printf("%s",buf);
reti = regexec(&reg,buf,0,NULL,0);
if(!reti) { //if there's a match
printf("%s",buf);
} else if(reti == REG_NOMATCH) {
printf("No match\n");
}
}

regfree(&reg);
}

int main(void) {
FILE *fp;

fp = fopen("./Hammer.data","r");

if(fp == NULL) {
perror("Error opening file");
return(-1);
}

for(int i = 0;i < 5;i++) {
search(fp, reports[i],i+1);
}

fclose(fp);

return(0);
}

Answer
while(fgets(buf,sizeof(buf),fp) != NULL) 

That will result in the fp pointing to the end of the file. So the next time the function is called the fgets will immediately return NULL. One fix is to rewind the file pointer before the fgets loop.