-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfunctions.c
1048 lines (919 loc) · 32.1 KB
/
functions.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
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "include/curl/curl.h"
#include "functions.h"
/**
* @Description Enumerator for integer conversions of c-interpretations of danish characters.
*/
enum danish_char {
ae = -90, oe = -72, aa = -91, AE = -122, OE = -104, AA = -123
};
/**
* @Description Enumerator for integer conversions of c-interpretations of miscellaneous characters, such as '©' .
*/
enum misc_char {
ö = -74,
Ö = -106,
ô = -76,
Ô = -108,
é = -87,
É = -119,
ä = -92,
Ä = -124,
ü = -68,
Ü = -100,
ñ = -79,
Ñ = -111,
TRADEMARK = -82,
SPACE = 32
};
/**
* @Description
* Reads a txt-file and parses for Bilka-products, which are then inserted into a linked list.
* @param file: file with non-COOP products
* @param head: head of linked-list
*/
void SallingScan(FILE* file, node** head) {
rewind(file);
char c;
while (feof(file) == 0) {
c = fgetc(file);
if (c == '"') {
char title[100];
char ctgry[100];
char desc[100] = "";
double price;
fscanf(file, "%[^\"]%*c", ctgry);
if (strcmp(ctgry, "title") == 0) {
fscanf(file, "%*2s%[^\"]%*c", title);
CheckOutputChar(title);
}
if (strcmp(ctgry, "description") == 0) {
fscanf(file, "\"%[^\"]", desc);
CheckOutputChar(desc);
if (strcmp(desc, title) == 0){
strcpy(desc, "");
}
//CheckOutputChar(desc);
}
if ((strcmp(ctgry, "price") == 0)) {
fscanf(file, "%*c%4lf", &price);
product newproduct;
strcpy(newproduct.name, title);
strcpy(newproduct.desc, desc);
strcpy(newproduct.store, "Bilka");
strcpy(newproduct.ean, "n/a");
newproduct.price = price;
InsertToList(head, newproduct);
}
}
}
}
/**
* @Description
* Reads a txt-file and parses for rema1000-products, which are then inserted into a linked list.
* @param file: file with non-COOP products
* @param head: head of linked-list
*/
void Rema1000Scan(FILE* file, node** head) {
rewind(file);
while (fgetc(file) != '[') {
}
char c;
while (1) {
c = fgetc(file);
if (feof(file)) {
break;
}
if (c == '"') {
char ctgry[100];
char desc[100];
double price;
fscanf(file, "%[^\"]%*c", ctgry);
if (strcmp(ctgry, "name") == 0) {
fscanf(file, "%*2s%[^\"]%*c", desc);
CheckOutputChar(desc);
}
if ((strcmp(ctgry, "price") == 0)) {
fscanf(file, "%*c%lf", &price);
product newproduct;
strcpy(newproduct.name, desc);
strcpy(newproduct.store, "Rema1000");
strcpy(newproduct.ean, "n/a");
newproduct.price = price;
InsertToList(head, newproduct);
}
}
}
}
void fotex_scan(FILE* file, node** head) {
while (fgetc(file) != '[') {
}
char c;
while (!feof(file)) {
c = fgetc(file);
if (c == '"') {
char ctgry[100];
char desc[300];
double price;
fscanf(file, "%[^\"]%*c", ctgry);
if (strcmp(ctgry, "name") == 0) {
fscanf(file, "%*2s%[^\"]%*c", desc);
CheckOutputChar(desc);
}
if ((strcmp(ctgry, "normalPrice") == 0)) {
fscanf(file, "%*c%lf", &price);
product newproduct;
strncpy(newproduct.name, desc, 30);
strcpy(newproduct.store, "Fotex");
newproduct.price = price / 100;
InsertToList(head, newproduct);
}
}
}
}
/**
* @Description
* function which asks the user for a desired product name and maximum number of items to be shown.
* @param name: string to contain user input of product name.
* @return user choice of maximum number of items that are to be shown in the terminal.
*/
int ScanInput(char* ProductName)
{
printf("Input the products name, like 'banan yoghurt'. Once you are done searching for \n products"
" you can end the program by typing 'end' and pressing enter>");
scanf(" %[^\n]s", ProductName);
if (strcasecmp(ProductName, "end") == 0) {
return 0;
}
while (getchar() != '\n');
while (1) {
printf("\nHow many results would you like to see for your product?>");
int num;
char term;
if (scanf("%d%c", &num, &term) != 2 || term != '\n') {
printf("Your input isn't a number. Try again :).\n");
while (getchar() != '\n');
continue;
}
else {
return num;
}
while (getchar() != '\n');
}
}
/**
* @Description
* Function which checks a string for uncommon characters, such as danish characters (æ, ø, å) or trademark-symbol,
* and then corrects them.
* @param string: string scanned from file
*
*/
void CheckOutputChar(char* string)
{
int len = strlen(string);
for (int i = 0; i < len; ++i) {
char* strB = NULL;
switch ((int)string[i]) {
case ae:
string[i - 1] = 'a';
string[i] = 'e';
break;
case oe:
string[i - 1] = 'o';
string[i] = 'e';
break;
case aa:
string[i - 1] = 'a';
string[i] = 'a';
break;
case AE:
string[i - 1] = 'A';
string[i] = 'E';
break;
case OE:
string[i - 1] = 'O';
string[i] = 'E';
break;
case AA:
string[i - 1] = 'A';
string[i] = 'A';
break;
case ö:
string[i - 1] = 'o';
string[i] = 'e';
break;
case Ö:
string[i - 1] = 'O';
string[i] = 'e';
break;
case ô:
strB = "o";
break;
case Ô:
strB = "O";
break;
case é:
strB = "e";
break;
case É:
strB = "E";
break;
case ä:
strB = "a";
break;
case Ä:
strB = "A";
break;
case ü:
strB = "u";
break;
case Ü:
strB = "U";
break;
case ñ:
strB = "n";
break;
case Ñ:
strB = "N";
break;
case TRADEMARK:
strB = "";
break;
}
if (strB != NULL) {
char* strA = string, strC[50];
strncpy(strC, strA, i - 1);
strC[i] = '\0';
strcat(strC, strB);
strcat(strC, strA + i + 1);
strcpy(string, strC);
}
}
}
/** Inserts a product into a linked list at the right place.
* @param head Head of the linked list.
* @param data The product struct
*/
void InsertToList(node** head, product data) {
node* newnode = malloc(sizeof(node));
newnode->data = data;
if (*head == NULL || (*head)->data.price >= newnode->data.price) {
newnode->next = *head;
*head = newnode;
}
else {
node* current = *head;
while (current->next != NULL && current->next->data.price < newnode->data.price) {
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}
char* GetSallingProducts(char* Item)
{
SAPIStruct SProducts;
strcpy(SProducts.URL, "https://api.sallinggroup.com/v1-beta/product-suggestions/relevant-products?query=");
strcat(SProducts.URL, Item);
strcpy(SProducts.RequestType, "GET");
strcpy(SProducts.PostFields, "");
strcpy(SProducts.KeyTypeAndKey, "Authorization: Bearer dc6422b7-166d-41e8-94c1-6804da7e17d5");
char* r = APICall(SProducts);
return r;
}
char* GetCoopProducts(char* Store)
{
SAPIStruct SProducts;
strcpy(SProducts.URL, "https://api.cl.coop.dk/productapi/v1/product/");
strcat(SProducts.URL, Store);
strcpy(SProducts.RequestType, "GET");
strcpy(SProducts.PostFields, "");
strcpy(SProducts.KeyTypeAndKey, "Ocp-Apim-Subscription-Key: fefba58d42c4456ca7182cc307574653");
char* r = APICall(SProducts);
return r;
}
char* GetFotexProducts(char query[])
{
SAPIStruct SProducts;
char entireQuery[300] = "{\"requests\":[{\"indexName\":\"prod_HD_PRODUCTS\",\"params\":\"query=";
char rest[200] = "&hitsPerPage=5&"
"page=0&"
"&attributesToRetrieve=%5B%22name%22%2C%22normalPrice%22%5D\"}]}";
strcat(entireQuery, query);
strcat(entireQuery, rest);
strcpy(SProducts.URL, "https://xpq5wkb9jp-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20JavaScript%203.21.1&x-algolia-application-id=XPQ5WKB9JP&x-algolia-api-key=a8f56e58f6db9e98065593bd33b60ddb");
strcpy(SProducts.RequestType, "POST");
strcpy(SProducts.PostFields, entireQuery);
char* response = APICall(SProducts);
return response;
}
char* GetRemaProducts(char query[])
{
SAPIStruct SProducts;
char entireQuery[300] = "{\"requests\":[{\"indexName\":\"aws-prod-products\",\"params\":\"query=";
char rest[200] = "&hitsPerPage=5000&"
"page=0&"
"&attributesToRetrieve=%5B%22name%22%2C%22labels%22%2C%22pricing%22%5D&attributesToHighlight=%5B%5D&attributesToSnippet=%5B%5D\"}]}";
strcat(entireQuery, query);
strcat(entireQuery, rest);
strcpy(SProducts.URL, "https://flwdn2189e-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20JavaScript%203.21.1&x-algolia-application-id=FLWDN2189E&x-algolia-api-key=fa20981a63df668e871a87a8fbd0caed");
strcpy(SProducts.RequestType, "POST");
strcpy(SProducts.PostFields, entireQuery);
char* response = APICall(SProducts);
return response;
}
void StoreChoice() {
FILE* stores;
char storeID[5];
char storeName[25];
printf("\nThis program can show you goods for: Bilka, Fakta, Dagli'Brugsen, Rema1000, 365 discount/365 & Fotex/Foetex");
printf("\nDue to problems with Salling Group and Coop, the program "
"can not show goods for other stores in these chains :( !\n\n");
stores = fopen("./stores.txt", "w");
printf("List your desired stores by entering a single store name and pressing enter.\nOnce done, type 'q' and press enter.\n\n");
//Loop for entering wanted stores
while (1) {
//Loop for avoiding blank inputs
while (printf("Enter store name>"
) && scanf("%[^\n]%*c", storeName) < 1) {
printf("Please give a valid input\n");
while (getchar() != '\n');
}
//Breaks loop
if (strcasecmp(storeName, "q") == 0) {
break;
}
//Check if entered store already is in list
if (StoreCheck(storeName) == 1) {
printf("\nSame store is already in list\n");
}
//Prints given store to list
else {
fprintf(stores, "%s\n", storeName);
printf("Given store is added to list\n\n");
}
}
fclose(stores);
//Prints stores present in list file
stores = fopen("./stores.txt", "r");
int i = 0;
while (!feof(stores)) {
++i;
fgets(storeName, 25, stores);
if (!feof(stores)) {
printf("Store number %d: %s\n", i, storeName);
}
}
fclose(stores);
}
//Function for checking if input store is already in list
int StoreCheck(char CurrentInput[])
{
FILE* stores;
int storeExists = 0;
char searchString[20];
strcpy(searchString, CurrentInput);
stores = fopen("./stores.txt", "r");
char buffer[20];
while (fgets(buffer, 20, stores)) {
char* checkForStore = strstr(buffer, searchString);
if (checkForStore != NULL) {
storeExists = 1;
break;
}
else {
storeExists = 0;
}
}
fclose(stores);
//Returns 1 if store is found in list
//Returns 0 if store is not found in list
return storeExists;
}
char* APICall(SAPIStruct Params)
{
/*Creates a handle*/
CURL* curl;
/*An enum representing the error state/code*/
CURLcode res;
/*This will init libcurls enviroment - CURL_GLOBAL_ALL should be used if you don't know what you are doing */
curl_global_init(CURL_GLOBAL_ALL);
/*Create an "easy handle", which is our handle to a transfer -> Handle part by which a thing is held, carried, or controlled. (manage)*/
curl = curl_easy_init();
/*https://curl.se/libcurl/c/curl_easy_setopt.html*/
struct string s;
if (curl)
{
InitString(&s);
/*Then set options in that handle to control the coming transfer*/
/*Here we set the path to Certificate Authority (CA) bundle*/
curl_easy_setopt(curl, CURLOPT_CAINFO, "cacert.pem");
/*Here we set the directory holding CA certificates*/
curl_easy_setopt(curl, CURLOPT_CAPATH, "cacert.pem");
/*Here we set the type of HTTP Request (GET, POST, DELETE etc.)*/
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, Params.RequestType);
/*The URL for this transfer*/
curl_easy_setopt(curl, CURLOPT_URL, Params.URL);
/*If relevant for the specific request, we pass a POSTField -> The data to POST. A post sends data to a server to create/update a resource*/
//If equal, it returns something different than 0
if (strcmp(Params.PostFields, "") != 0) {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, Params.PostFields);
}
/*1L tells libCurl to follow all the redirects we may get from the request*/
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/*Specify the protocol to use, HTTPS or rest etc.*/
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
/*Set's a callback function (function called by function) to receive incoming data myfunc);*/
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteFunc);
/*-----------------------------------------------------------*/
/*Callback will take an argument that is set (This is our string)*/
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/*-----------------------------------------------------------*/
/*Creates a LinkedList for our Headers*/
struct curl_slist* headers = NULL;
/*If relevant adds our key type and key to the headers*/
if (strcmp(Params.KeyTypeAndKey, "") != 0) {
headers = curl_slist_append(headers, Params.KeyTypeAndKey);
}
/*Set's our encoding type, decided by the API provider. Could have been multipart/form-data, this is for binary data though*/
headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
/*Passes our headers LinkedList, to curl as headers*/
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
/*Delete the linked list*/
curl_slist_free_all(headers);
/*Cleanup after easy curl*/
curl_easy_cleanup(curl);
}
/*Cleanup after curl*/
curl_global_cleanup();
return s.ptr;
}
/*________________________________________________________________________________*/
//All code between the these^^ (Line 492-523) is from stackoverflow - this seems like the only way to really do this
//https://stackoverflow.com/a/2329792
/** Initialises our string struct
* @param string* s, a pointer to the specifc struct we wants to init
* */
void InitString(struct string* s) {
//set the length to 0
s->len = 0;
s->ptr = malloc(s->len + 1);
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
//terminate it with '\0', we have to make sure
s->ptr[0] = '\0';
}
/** This function recieves all of the data chunks from libcurl + our string struct
* void* is a void pointer, a void pointer can hold address of any type (like char & int)
* and can be typecasted to any type
* @param void* ptr takes incoming data chunks from libcurl, specifically the characters
* @param size_t size incoming data chunks, specifically the size of our elements byte size (like char = 1 byte, int = 2 - 4 bytes)
* @param size_t nmemb incoming data chunks, specifically the number of elements
* @param string *s our string struct
* */
size_t WriteFunc(void* ptr, size_t size, size_t nmemb, struct string* s)
{
//Calculate how much space we need to realloc
size_t new_len = s->len + size * nmemb;
//realloc our string to match the size of the size of our incoming data + whatever we already are storing in it
s->ptr = realloc(s->ptr, new_len + 1);
//this failure shouldn't happen - better to be sure though
if (s->ptr == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
//copies our data from the ptr, to our string
memcpy(s->ptr + s->len, ptr, size * nmemb);
//makes sure we terminate the string with '\0' as all strings should be
s->ptr[new_len] = '\0';
//updates the length, if we need to realloc more data
s->len = new_len;
return size * nmemb;
}
/*________________________________________________________________________________*/
/** Calls the non-coop APIs and inserts the searched product in a list.
* @param Item Query string used for looking the right product up
* @param Dictionary SDictionary struct that contains information about stores
* @param LinkedList The head of the linked list
*/
void GetNonCoopProducts(char* Item, SDictionary Dictionary, node** LinkedListHead) {
FILE* QFile;
QFile = fopen("QueryResults.txt", "w+");
FILE* StoreFile;
StoreFile = fopen("stores.txt", "r");
char buffer[20];
Item[strcspn(Item, "\n")] = '\0';
while (fgets(buffer, 15, StoreFile))
{
//Fjerner alle \n fra vores buffer, dette gør det muligt at søge på alle linjer, ellers ville search slå fejl for alle udover den sidste
buffer[strcspn(buffer, "\n")] = '\0';
char* Key;
char IsDigkey[20];
Key = DictionaryLookup(Dictionary, buffer);
if (Key == NULL)
{
printf("Store not found\n");
}
else {
strcpy(IsDigkey, Key);
if (!strcasecmp(Key, "Rema") || !strcasecmp(Key, "Rema1000") && !isdigit(IsDigkey[0]))
{
freopen("QueryResults.txt", "w+", QFile);
char* c = GetRemaProducts(Item);
fputs(c, QFile);
rewind(QFile);
Rema1000Scan(QFile, LinkedListHead);
free(c);
}
else if (!strcmp(Key, "Fotex")) {
freopen("QueryResults.txt", "w+", QFile);
char* c = GetFotexProducts(Item);
fputs(c, QFile);
rewind(QFile);
fotex_scan(QFile, LinkedListHead);
free(c);
}
else if (!isdigit(IsDigkey[0])) {
freopen("QueryResults.txt", "w+", QFile);
char* c = GetSallingProducts(Item);
fputs(c, QFile);
rewind(QFile);
SallingScan(QFile, LinkedListHead);
free(c);
}
}
}
fclose(QFile);
fclose(StoreFile);
}
/* Deletes all existing items in a given list by freeing the memory, takes the head of the LinkedList as a param */
void DeleteAllListItems(node** LinkedListHead)
{
node* current = *LinkedListHead;
while (current != NULL) {
node* next = current->next;
free(current);
current = next;
}
*LinkedListHead = NULL;
}
/*Calls the API's and writes the data to a file*/
void WriteCoopDataToFile(char* Item, SDictionary Dictionary, int Runs)
{
FILE* QFile;
QFile = fopen("CoopQueryResults.txt", "a");
FILE* StoreFile;
StoreFile = fopen("stores.txt", "r");
char buffer[20];
Item[strcspn(Item, "\n")] = '\0';
while (fgets(buffer, 15, StoreFile))
{
//Fjerner alle \n fra vores buffer, dette gør det muligt at søge på alle linjer, ellers ville search slå fejl for alle udover den sidste
buffer[strcspn(buffer, "\n")] = '\0';
char IsDigkey[20];
char* Key;
Key = DictionaryLookup(Dictionary, buffer);
if (Key == NULL)
{
printf("Store not found\n");
}
else {
strcpy(IsDigkey, Key);
if (isdigit(IsDigkey[0]))
{
if (Runs == 0)
{
char* c = GetCoopProducts(Key);
fputs(c, QFile);
fputs("??", QFile);
free(c);
}
}
}
}
fclose(QFile);
fclose(StoreFile);
}
/*This initializes our dictionary (Gives it all of the entries with keys and values)*/
SDictionary InitDictionary()
{
//Create the dictionary
SDictionary Dictionary;
/*https://stackoverflow.com/a/62004489*/
//If you pass NULL to realloc(),
//then realloc will try to allocate a completely new block of RAM,
//but if you pass something different than NULL it, realloc suposses that it already exists (in RAM)
//and will therefor try to realloc an existing block of RAM (which it isn't) and the computer dies.
Dictionary.entry = NULL;
/*Creates our entry for Dagli'Brugsen*/
SDictEntry EntryDagliBrugs;
strcpy(EntryDagliBrugs.Key, "Dagli'Brugsen");
strcpy(EntryDagliBrugs.Value, "2082");
/*Update the dictionary, first update the length, then update the entry*/
Dictionary.DictLength = 1;
Dictionary.DictMaxSize = 10;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[0] = EntryDagliBrugs;
SDictEntry EntryBilka;
strcpy(EntryBilka.Key, "Bilka");
strcpy(EntryBilka.Value, "Bilka");
Dictionary.DictLength = 2;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[1] = EntryBilka;
/*Creates our entry for Fakta*/
SDictEntry EntryFakta;
strcpy(EntryFakta.Key, "Fakta");
strcpy(EntryFakta.Value, "24080");
/*Updates our dictonaries length, and adds the new entry to the dictionary*/
Dictionary.DictLength = 3;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[2] = EntryFakta;
SDictEntry EntryRema;
strcpy(EntryRema.Key, "Rema");
strcpy(EntryRema.Value, "Rema");
Dictionary.DictLength = 4;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[3] = EntryRema;
SDictEntry EntryRema2;
strcpy(EntryRema2.Key, "Rema1000");
strcpy(EntryRema2.Value, "Rema");
Dictionary.DictLength = 5;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[4] = EntryRema2;
SDictEntry EntryFotex;
strcpy(EntryFotex.Key, "Fotex");
strcpy(EntryFotex.Value, "Fotex");
Dictionary.DictLength = 6;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[5] = EntryFotex;
SDictEntry EntryFoetex;
strcpy(EntryFoetex.Key, "Foetex");
strcpy(EntryFoetex.Value, "Fotex");
Dictionary.DictLength = 7;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[6] = EntryFoetex;
SDictEntry Entry365;
strcpy(Entry365.Key, "365");
strcpy(Entry365.Value, "24161");
Dictionary.DictLength = 8;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[7] = Entry365;
SDictEntry Entry365Disc;
strcpy(Entry365Disc.Key, "365 discount");
strcpy(Entry365Disc.Value, "24161");
Dictionary.DictLength = 9;
Dictionary.entry = realloc(Dictionary.entry, Dictionary.DictLength * sizeof(SDictEntry));
Dictionary.entry[8] = Entry365Disc;
return Dictionary;
}
/*This is a given, it looks up in our dictionary, this is done with a "Key"*/
char* DictionaryLookup(SDictionary Dictionary, char* Key)
{
//For the size of our dictionary
for (int i = 0; i < Dictionary.DictLength; i++)
{
//If equal, it returns 0, therefor we want !strcmp (Some might be used to it returning 1)
/*This checks if our key, is equal to the set key, of the dictionary entry*/
if (!strcasecmp(Dictionary.entry[i].Key, Key))
{
//If they are equal, return the value
return Dictionary.entry[i].Value;
}
}
return NULL;
}
void FinalPrint(struct node* head, int MaxItems)
{
printf("\n");
printf("____________________________________________________________________________________\n");
printf("| Product | Price | Store |\n");
printf("| | | |\n");
node* current = head;
for (int i = 0; i < MaxItems; i++)
{
if (current == NULL) {
break;
}
if (strcmp(current->data.desc, "") != 0)
{
strcat(current->data.name, " ");
strcat(current->data.name, current->data.desc);
}
printf("|%49s |%14.2lf |%14s |\n", current->data.name, current->data.price, current->data.store);
current = current->next;
}
printf("____________________________________________________________________________________\n\n");
}
product* coop_scan(FILE* file, int* counter, char* Store) {
FILE* XFile;
XFile = fopen("CoopQueryResults.txt", "r");
while (1) {
char b = fgetc(XFile);
if (feof(XFile)) {
break;
}
if (b == '}') {
*counter += 1;
}
}
fclose(XFile);
product* products = malloc(sizeof(product) * *counter);
char c;
int i = 0;
while (1) {
c = fgetc(file);
if (feof(file)) {
break;
}
if (c == '?') {
char c2;
c2 = fgetc(file);
if (c2 == '?')
{
return products;
}
}
if (c == '"') {
char ctgry[100];
char ean[13];
char desc[100];
char desc2[100];
double price;
fscanf(file, "%[^\"]%*c", ctgry);
if (strcmp(ctgry, "Ean") == 0) {
fscanf(file, "%*2s%[^\"]%*c", ean);
strcpy(products[i].ean, ean);
}
if (strcmp(ctgry, "Navn") == 0) {
fscanf(file, "%*2s%[^\"]%*c", desc);
CheckOutputChar(desc);
strcpy(products[i].name, desc);
strcpy(products[i].store, Store);
}
//Add navn2 to navn
FILE* NFile;
NFile = fopen("CoopQueryResults.txt", "r");
long cptr = ftell(file);
fseek(NFile, cptr, SEEK_SET);
char Navn2Check[200];
char navn2[100];
if (fgets(Navn2Check, 200 ,NFile) != NULL){
char *navn2_pointer = strstr(Navn2Check, "Navn2");
sscanf(navn2_pointer, "Navn2\":\"%[^\"]", navn2);
if (navn2_pointer != NULL)
{
if (strstr(navn2, "\"\"")) {
strcpy(products[i].desc, "");
} else {
strcpy(products[i].desc, navn2);
}
}
}
fclose(NFile);
/*This really doesn't do anything, but if it isn't here, the code breaks - it's probably moving the cursor*/
/*DO NOT TOOOOOOUUUUCHHHHHH*/
if (strcmp(ctgry, "Navn2") == 0) {
fscanf(file, "%*[\"]%*[\"]%s%[^\"]", desc2);
if (strcmp(desc2, "\"") == 0) {
}
/*else {
//fscanf(file, "%*2s%[^\"]%*c", desc);
strcat(products[i].name, desc2);
}*/
}
/*-------------------------------------------------------------------------------------------------------*/
if ((strcmp(ctgry, "Pris") == 0)) {
fscanf(file, "%*c%lf", &price);
products[i].price = price;
i += 1;
}
}
}
return products;
}
void ReadCoopData(char* Query, node** ProductList)
{
FILE* QFile;
QFile = fopen("CoopQueryResults.txt", "r");
int ArraySize = 0;
FILE* SFile;
SFile = fopen("stores.txt", "r");
char buffer[20];
for (int i = 0; Query[i] != '\0'; i++)
{
Query[i] = toupper(Query[i]);
}
while (fgets(buffer, 50, SFile)) {
buffer[strcspn(buffer, "\n")] = '\0';
if (strcasecmp(buffer, "Fakta") == 0)
{
RelevantCoopData(QFile, "Fakta", Query, ProductList);
}
if (strcasecmp(buffer, "Dagli'Brugsen") == 0)
{
RelevantCoopData(QFile, "Dagli'Brugsen", Query, ProductList);
}
if (strcasecmp(buffer, "365 discount") == 0)
{
RelevantCoopData(QFile, "365 Discount", Query, ProductList);
}
if (strcasecmp(buffer, "365") == 0)
{
RelevantCoopData(QFile, "365 Discount", Query, ProductList);
}
}
}
void RelevantCoopData(FILE* QFile, char* Store, char* Query, node** LinkedList)
{
Query[strcspn(Query, "\n")] = '\0';
int ArrayIndex = 0;
product* AllProducts = coop_scan(QFile, &ArrayIndex, Store);
for (int i = 0; i < ArrayIndex; i++)
{
if (strstr(AllProducts[i].name, Query) != NULL)
{
if (IsProductInList(*LinkedList, AllProducts[i]))
{
}
else {
InsertToList(LinkedList, AllProducts[i]);
}
}
}
free(AllProducts);
}
int IsProductInList(node* LinkedList, product data)
{
node* current = LinkedList;
while (current != NULL)
{
if (strcmp(current->data.ean, data.ean) == 0)
{
if (strcmp(current->data.store, data.store) == 0)
{
return 1;
}
}
current = current->next;
}
return 0;
}
/**
* @Description