-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathchall.c
More file actions
120 lines (106 loc) · 2.69 KB
/
Copy pathchall.c
File metadata and controls
120 lines (106 loc) · 2.69 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define NUM_HASHTABLE 20
int setup(){
setvbuf(stdin,NULL,_IONBF,0);
setvbuf(stdout,NULL,_IONBF,0);
}
typedef struct
{
int key;
char value[8];
} hashEntry;
typedef struct
{
size_t size;
hashEntry *entries;
} hashTable;
hashTable hashTables[NUM_HASHTABLE];
hashEntry empty = {0};
int allocHashTable(size_t size, hashTable *ptr){
hashEntry *entries = malloc(size*sizeof(hashEntry));
if (entries == NULL) return 1;
ptr->size = size;
ptr->entries = entries;
return 0;
}
hashEntry *getHashTable(hashTable *table, int key){
size_t index = key % (table->size);
hashEntry *entries = table->entries;
while (entries[index].key != key){
if (memcmp(&empty, &(entries[index]), sizeof(hashEntry)) == 0)
break; // if hash entry is all 0 bytes then assume it is empty
index = index + 1;
}
return &(entries[index]);
}
void menu(){
printf("1. New Hash Table\n2. Set\n3. Get\n4. Exit\n");
}
int getChoice(){
int result;
printf("> ");
scanf("%d", &result);
getc(stdin);
return result;
}
int main(){
setup();
menu();
int repeat = 1;
int index, key;
size_t size;
hashEntry *entry;
while (repeat)
{
int choice = getChoice();
switch (choice)
{
case 1:
printf("Index: ");
scanf("%d", &index);
if (0 > index || index >= NUM_HASHTABLE) exit(0);
if (hashTables[index].entries != NULL){
printf("That index has been used\n");
break;
}
printf("Size: ");
scanf("%ld", &size);
if (allocHashTable(size, &(hashTables[index]))){
printf("Allocation failed");
exit(0);
}
break;
case 2:
printf("Index: ");
scanf("%d", &index);
printf("Key: ");
scanf("%d", &key);
entry = getHashTable(&(hashTables[index]), key);
entry->key = key;
printf("Value: ");
read(0, entry->value, 8);
break;
case 3:
printf("Index: ");
scanf("%d", &index);
printf("Key: ");
scanf("%d", &key);
entry = getHashTable(&(hashTables[index]), key);
if (entry->key != key){
printf("Not found\n");
break;
}
printf("Value: %.8s", entry->value);
break;
case 4:
repeat = 0;
break;
default:
printf("That is not an option\n");
break;
}
}
}