-
Notifications
You must be signed in to change notification settings - Fork 0
/
my_grep
150 lines (129 loc) · 2.42 KB
/
my_grep
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_PATH_LENGTH 255
int KMP (char s[], char p[])
{
int i, j, N, M;
N = strlen(s);
M = strlen(p);
int *d =(int*)malloc(M*sizeof(int));
d[0]=0;
for(i=1,j=0;i<M;i++)
{
while(j>0 && p[j]!=p[i])
j = d[j-1];
if(p[j]==p[i])
j++;
d[i]=j;
}
for(i=0,j=0;i<N; i++)
{
while(j>0 && p[j]!=s[i])
j=d[j-1];
if(p[j]==s[i])
j++;
if (j==M)
{
free (d);
return i-j+1;
}
}
free (d);
return -1;
}
//возращаем номер образца в argv
int read_args( int argc, char** argv, int *is_file)
{
if (argc<3){
printf("input error: few arguments\n");
exit(1);
}
struct stat buff;
if (stat(argv[2], &buff)<0) {
perror(argv[2]);
exit(1);
}
if(S_ISDIR(buff.st_mode))
*is_file=0;
else
*is_file=1;
return 1;
}
void find_in_file( char *sample, char *src)
{
printf("%s: \n", src);
char *buff=(char*)malloc(255*sizeof(char));
FILE *file=fopen(src, "r");
if( file==NULL ){
printf("error: %s not found\n", src);
return;
}
int i=0;
int num_str=0;
while (1)
{
int ch = getc(file);
buff[(i++)%256]=ch;
buff[(i+1)%256]='\0';
if (feof(file))
break;
else if (ch == '\n') {
if ( KMP(buff, sample)>=0 ){
printf(" %s",buff);
++num_str;
}
i=0;
}
}
if(num_str==0) printf(" none\n");
fclose(file);
free(buff);
}
void find_in_dir(char *sample, char *src)
{
struct stat buf;
DIR *dir=opendir(src);
if(dir==NULL) {
perror(src);
return;
}
struct dirent *curr_dir;
while ( (curr_dir = readdir(dir)) != NULL)
{
if (curr_dir->d_name[0]!='.') {
strcat(src, "/");
strcat(src, curr_dir->d_name);
if (stat(src, &buf) < 0)
perror(curr_dir->d_name);
else if( S_ISDIR(buf.st_mode) ) {
find_in_dir(sample, src);
}
else
find_in_file(sample, src);
int i;
for(i=strlen(src)-1; src[i]!='/' && i>0; --i) src[i]='\0';
src[i]='\0';
}
}
closedir(dir);
return;
}
int main(int argc, char** argv)
{
int is_file=0;
int sample_order = read_args(argc, argv, &is_file);
if(is_file) find_in_file (argv[sample_order], argv[sample_order+1]);
else {
char src[MAX_PATH_LENGTH]="";
strcat(src, argv[argc-1]);
find_in_dir(argv[sample_order], src);
}
exit(0);
}