From 8f42003b7dcc6c39e3894baebac2bbc055083830 Mon Sep 17 00:00:00 2001 From: KRUGSON Date: Tue, 7 Feb 2023 15:14:42 +0100 Subject: [PATCH] refactoring: added function to read files --- src/c/items.c | 7 +------ src/c/main.c | 7 +------ src/c/map.c | 7 +------ src/c/nav_helper.c | 17 ++++++++++++++++- src/c/nav_helper.h | 3 +++ 5 files changed, 22 insertions(+), 19 deletions(-) diff --git a/src/c/items.c b/src/c/items.c index e44fdbc..930e59e 100644 --- a/src/c/items.c +++ b/src/c/items.c @@ -15,12 +15,7 @@ Item *getItems(char *itemsMapFile) size_t len = 0; ssize_t read; - stream = fopen(itemsMapFile, "r"); - if (stream == NULL) - { - printf("ERROR: couldn't open or find file: ITEMS!\n"); - exit(EXIT_FAILURE); // exit - } + stream = getStream(itemsMapFile); char delimiter[] = ";"; diff --git a/src/c/main.c b/src/c/main.c index 0396155..971f88e 100644 --- a/src/c/main.c +++ b/src/c/main.c @@ -73,12 +73,7 @@ void printInit() size_t len = 0; ssize_t read; - stream = fopen(gameInstructionsFile, "r"); - if (stream == NULL) - { - printf("ERROR: couldn't open or find file: INSTRUCTIONS !\n"); - exit(EXIT_FAILURE); // exit - } + stream = getStream(gameInstructionsFile); /* print line by line from file */ while ((read = getline(&line, &len, stream)) != -1) diff --git a/src/c/map.c b/src/c/map.c index 1221b8f..a4b3d3b 100644 --- a/src/c/map.c +++ b/src/c/map.c @@ -10,12 +10,7 @@ Room *getMap(char *gameMapFile) size_t len = 0; ssize_t read; - stream = fopen(gameMapFile, "r"); - if (stream == NULL) - { - printf("ERROR: couldn't open or find file: MAP!\n"); - exit(EXIT_FAILURE); // exit - } + stream = getStream(gameMapFile); char delimiter[] = ";"; diff --git a/src/c/nav_helper.c b/src/c/nav_helper.c index e36961d..78bdeb7 100644 --- a/src/c/nav_helper.c +++ b/src/c/nav_helper.c @@ -1,4 +1,6 @@ //bibs +#include +#include #include //headers @@ -9,4 +11,17 @@ bool startsWith(const char *a, const char *b) if (strncmp(a, b, strlen(b)) == 0) return 1; return 0; -}; \ No newline at end of file +}; + +FILE *getStream(char *filePath) +{ + FILE *stream; + stream = fopen(filePath, "r"); + if (stream == NULL) + { + printf("ERROR: couldn't open or find file: %s !\n", filePath); + exit(EXIT_FAILURE); // exit + } + + return stream; +} diff --git a/src/c/nav_helper.h b/src/c/nav_helper.h index 9e513d2..f90f1c2 100644 --- a/src/c/nav_helper.h +++ b/src/c/nav_helper.h @@ -1,9 +1,12 @@ #ifndef NAV_HELPER_H #define NAV_HELPER_H +#include +#include #include #include bool startsWith(const char *a, const char *b); +FILE *getStream(char *filePath); #endif \ No newline at end of file