-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfnmatch.c
75 lines (65 loc) · 1.59 KB
/
fnmatch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fnmatch.h>
#define MAX_KEYS 1000
int main(int argc, char ** argv)
{
const char * key = argv[2];
const char * file = argv[3];
int lineNum = 0;
int offset = 0;
int i = 0;
char * keyArray[MAX_KEYS]; // Array to store keys of input
int offsetArray[MAX_KEYS]; // Array to store offset of start of the line
char * line = NULL;
char * token = NULL;
size_t len = 0;
size_t read;
int loc;
memset(offsetArray, 0, MAX_KEYS * sizeof(int));
FILE * fp = fopen(file, "r");//Open file
if(NULL == fp)
{
printf("Input file not found.\n");
return -1;
}
while ((read = getline(&line, &len, fp)) != -1) //Read line one by one
{
if(strstr(line, ","))
{
token = strtok(line, ","); // store the first token
int tokLen = strlen(token);
keyArray[lineNum] = (char *)malloc((tokLen + 1) * sizeof(char));
strcpy(keyArray[lineNum],token);
}
else
{
keyArray[lineNum] = (char *)malloc((read + 1) * sizeof(char));
strncpy(keyArray[lineNum], line, read -1); // -1 is to remove the trailing '\n'
}
offsetArray[lineNum] = offset;
lineNum++;
offset += read;
}
lineNum -= 1;
//Search for the key in file
for(i = 0; i <= lineNum; i++) /* cleanup the memory allocated for key array */
{
loc = fnmatch(keyArray[i],key,0);
}
if(loc >= 0) // Match found
{
fseek(fp, offsetArray[loc], SEEK_SET);
getline(&line, &len, fp);
printf("%s", line);
}
fclose(fp);
if (line)
free(line); //free lines
for(i = 0; i <= lineNum; i++) // clean the memory
{
free(keyArray[i]);
}
return 0;
}