/
TestSearch.c
108 lines (96 loc) · 2.49 KB
/
TestSearch.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
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
/*********************************************************
* Test Program for searching with LinkedLists.h
* @author - Alex Wilson atw9262
*********************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "LinkedLists.h"
/*
* @param Linked List, word to search for
* @return Index of word, -1 if not found
*/
int searchList(LinkedLists *list, char *word){
char *currentWord;
int index,done;
ElementStructs *currentElement;
do{
done = 1;
currentElement = RemoveFromFrontOfLinkedList(list);
if(currentElement != NULL){
done = 0;
currentWord = currentElement->word;
index = currentElement->index;
free(currentElement);
if(strcmp(currentWord, word) == 0){
free(currentWord);
return index;
}
free(currentWord);
}
}while(done != 1);
return -1;
}
int main(int argc, char** argv){
FILE *input;
int c = 0, searchIndex, i;
char *searchWord;
LinkedListNodes *listNode;
LinkedLists *list = malloc(sizeof(LinkedLists));
InitLinkedList(list);
if(argc == 2){
/* Correct number of arguments */
input = fopen(argv[1],"r+");
if(input != NULL){
do{
ElementStructs *element;
char *word = malloc(80);
if(!feof(input)){
fscanf(input, "%s", word);
element = malloc(sizeof(ElementStructs));
element->word = word;
element->index = c;
AddToBackOfLinkedList(list, element);
c++;
}else{
free(word);
}
}while(!feof(input));
printf("Words: %d\n",c);
/* First 6 elements */
listNode = list->FrontPtr;
for(i = 0;i < 6;i++){
printf("%s\n", listNode->ElementPtr->word);
listNode = listNode->Next;
}
/* Last 6 elements */
listNode = list->BackPtr;
for(i = 0;i < 6;i++){
printf("%s\n", listNode->ElementPtr->word);
listNode = listNode->Previous;
}
printf("\n-------------------------------------------------------------------\n");
searchWord = malloc(80);
printf("Please enter the word you would like to search for: ");
scanf("%s",searchWord);
searchIndex = searchList(list, searchWord);
if(searchIndex < 0){
printf("Your string was not found\n");
}else{
printf("The string: %s was found at index: %d\n",searchWord,searchIndex);
}
free(searchWord);
}else{
printf("File: %s could not be opened\n",argv[1]);
return 2;
}
fclose(input);
}else{
/* Usage message */
printf("Usage: %s <input file>\n",argv[0]);
return 1;
}
DestroyLinkedList(list);
free(list);
return 0;
}