-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.c
103 lines (92 loc) · 2.97 KB
/
map.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
//
// Created by Jesko Förster on 18.04.2024.
//
#include <sys/shm.h>
#include <stdlib.h>
#include "map.h"
void map_insert_element(Map* map, const char* key, const char* value) {
// Check if the key already exists and update the value if found
for (int i = 0; i < MAP_SIZE; i++) {
if (strcmp(map->table[i].key, key) == 0) {
// Key already exists, update the value
int valueSize = sizeof(map->table[i].value) - 1;
strncpy(map->table[i].value, value, valueSize);
map->table[i].value[valueSize] = '\0';
return;
}
}
// Key not found, search for an empty slot
for (int i = 0; i < MAP_SIZE; i++) {
if (map->table[i].key[0] == '\0') {
// Found an empty slot, insert the new entry
int valueSize = sizeof(map->table[i].value) - 1;
int keySize = sizeof(map->table[i].key) - 1;
strncpy(map->table[i].key, key, keySize);
map->table[i].key[keySize] = '\0';
strncpy(map->table[i].value, value, valueSize);
map->table[i].value[valueSize] = '\0';
return;
}
}
// Array is fully occupied
printf("The storage is full, no further values can be saved.\n");
}
const char* map_get_element(Map* map, const char* key) {
// Check if the key exists
for (int i = 0; i < MAP_SIZE; i++) {
if (strcmp(map->table[i].key, key) == 0) {
// Key found, return the value
return map->table[i].value;
}
}
// Key not found
return NULL;
}
char* map_getall_elements(Map* map) {
char* results = malloc(100*MAP_SIZE * sizeof(char));
char ending[4];
sprintf(ending,"\n\r");
for (int i = 0; i < MAP_SIZE; i++) {
if (strcmp(map->table[i].key,"")!=0) {
strcat(results, map->table[i].key);
strcat(results, " ");
strcat(results, map->table[i].value);
strcat(results, ending);
}
}
return results;
}
void map_delete_element(Map* map, const char* key) {
// Check if the key exists
for (int i = 0; i < MAP_SIZE; i++) {
if (strcmp(map->table[i].key, key) == 0) {
// Key found, delete the entry
map->table[i].key[0] = '\0';
map->table[i].value[0] = '\0';
return;
}
}
}
void map_deleteall_elements(Map* map) {
for (int i = 0; i < MAP_SIZE; i++) {
if (map->table[i].key != NULL) {
map->table[i].key[0] = '\0';
map->table[i].value[0] = '\0';
}
}
}
Map * createSharedMemoryMap(){
// Erstellen des Shared Memory
int shmid = shmget(IPC_PRIVATE, sizeof(Map), IPC_CREAT|0600);
if (shmid == -1) {
perror("shmget failed");
exit(EXIT_FAILURE);
}
// Anhängen des Shared Memory an den Prozess
Map * shar_mem_map = (Map *)shmat(shmid, 0, 0);
if (shar_mem_map == (void *)-1) {
perror("shmat failed");
exit(EXIT_FAILURE);
}
return shar_mem_map;
}