#include "utilities/IOUtilities.h" #include #include #include #include "shell/Shell.h" #include "utilities/AutoFreePool.h" #include "utilities/JSONParser.h" bool readBytesFromMemoryBlock(const void * buffer, size_t bufferSize, size_t * offset, size_t length, void * target) { if ((length + *offset) > bufferSize) { return false; } if (target != NULL) memcpy(target, (buffer + *offset), length); *offset += length; return true; } void * readFileSimple(const char * filePath, size_t * outFileLength) { FILE * file; size_t fileLength; void * fileContents; file = fopen(filePath, "rb"); if (file == NULL) { return NULL; } fseek(file, 0, SEEK_END); fileLength = ftell(file); fseek(file, 0, SEEK_SET); fileContents = malloc(fileLength); fread(fileContents, 1, fileLength, file); fclose(file); if (outFileLength != NULL) *outFileLength = fileLength; return fileContents; } const char * resourcePath(const char * filePath) { static char * path; path = malloc(PATH_MAX); snprintf(path, PATH_MAX, "%s/%s", Shell_getResourcePath(), filePath); AutoFreePool_add(path); return path; } const char * worldPath(const char * fileName) { static char * path; path = malloc(PATH_MAX); // HACK test_world; should retrieve from state object that stores current world, optionally passed as arg to this function snprintf(path, PATH_MAX, "%s/test_world/%s", Shell_getResourcePath(), fileName); AutoFreePool_add(path); return path; } struct JSONNode * jsonFromFile(const char * filePath) { void * fileContents; size_t fileLength; JSONNode * result; fileContents = readFileSimple(filePath, &fileLength); if (fileContents == NULL) { fprintf(stderr, "Warning: %s failed to open\n", filePath); return NULL; } result = JSONParser_parse(fileContents, fileLength); free(fileContents); if (result == NULL) { fprintf(stderr, "Warning: %s failed to parse as JSON\n", filePath); } return result; }