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
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct WRD {
char * text;
struct WRD * next;
} wrd_t;
wrd_t * new_word(const char * s, wrd_t * last);
wrd_t * words_from_file(const char * file_name);
void print_contains(const wrd_t * list, const char * s);
void delete_words(wrd_t * list);
int main(void){
char buf[BUFSIZ];
wrd_t * list;
printf("Name of input file: ");
if ( scanf("%s", buf) != 1 ){
perror("scanf");
exit(EXIT_FAILURE);
}
if ( ( list = words_from_file(buf) ) == NULL ){
fprintf(stderr, "Can't get words from file %s\n", buf);
exit(EXIT_FAILURE);
}
printf("What to searching for: ");
if ( scanf("%s", buf) != 1 ){
perror("scanf");
delete_words(list);
exit(EXIT_FAILURE);
}
print_contains(list, buf);
delete_words(list);
exit(EXIT_SUCCESS);
}
wrd_t * new_word(const char * s, wrd_t * last){
wrd_t * w;
if ( ( w = (wrd_t*)malloc(sizeof(wrd_t)) ) == NULL )
return NULL;
if ( ( w->text = strdup(s) ) == NULL ){
free(w);
return NULL;
}
w->next = NULL;
if ( last )
last->next = w;
return w;
}
wrd_t * words_from_file(const char * file_name){
FILE * f;
wrd_t * first, * last;
static char buf[BUFSIZ];
if ( ( f = fopen(file_name, "r") ) == NULL )
return NULL;
first = last = NULL;
while ( fscanf(f, "%s", buf) == 1 ){
if ( ( last = new_word(buf, last) ) == NULL )
return NULL;
if ( ! first )
first = last;
}
fclose(f);
return first;
}
void print_contains(const wrd_t * list, const char * s){
while ( list ){
if ( strstr(list->text, s) )
printf("%s\n", list->text);
list = list->next;
}
}
void delete_words(wrd_t * list){
wrd_t * tmp;
while ( list ){
tmp = list->next;
free(list->text);
free(list);
list = tmp;
}
} |