I've been having problems lately trying to do pattern matching in C while implementing wildcards. Take for instance the following code:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
void grepwc(char *b) {
FILE *fp;
fp = fopen("/var/log/apache2/other_vhosts_access.log", "r");
char line[100];
unsigned int i = 0;
while(fgets(line, sizeof(line), fp)) {
if (strstr(line, b) != NULL) {
i++;
}
}
printf("%s %d\n", b, i);
fclose(fp);
}
int main() {
time_t current = time(NULL);
char date_time[10];
char newhold[34];
/* strftime(date_time, sizeof(date_time), "%d", localtime(¤t));
strncat( newhold, date_time, 10 );
strncat( newhold, "?", 2 );
strftime(date_time, sizeof(date_time), "%b", localtime(¤t));
strncat( newhold, date_time, 10 );
strncat( newhold, "*", 2 ); */
strncat( newhold, "pattern", 10 );
grepwc(newhold);
return 0;
}
With what I have commented out it looks for the word "pattern" in a log file and counts each match:
$ ./test
pattern 2
I should note that output may look a little broken depending on your architechure of processor. This is the file I am gathering this from right now:
$ cat /var/log/apache2/other_vhosts_access.log
01 Jul pattern
pattern
However, if we uncomment these lines:
strftime(date_time, sizeof(date_time), "%d", localtime(¤t));
strncat( newhold, date_time, 10 );
strncat( newhold, "?", 2 );
strftime(date_time, sizeof(date_time), "%b", localtime(¤t));
strncat( newhold, date_time, 10 );
strncat( newhold, "*", 2 );
The date is not matched:
$ ./test
01?Jul*pattern 0
I've tried searching some lots pattern matching tutorials in C and even tried applying some regex. The best I got was to get this to work with only one wildcard, but I'm needing to get this to work with 2 or more. Any suggestions greatly appreciated.