all repos — hex @ ca765f7c2550b7594b8819b0f9f823c8b452e49d

A tiny, minimalist, slightly-esoteric concatenative programming lannguage.

Fixes.
h3rald h3rald@h3rald.com
Fri, 22 Nov 2024 19:09:38 +0100
commit

ca765f7c2550b7594b8819b0f9f823c8b452e49d

parent

d51f1d99f712c3df7e91b43bf2831ec3315a7e7a

2 files changed, 50 insertions(+), 18 deletions(-)

jump to
M hex.chex.c

@@ -3548,39 +3548,67 @@

// Read a file into a buffer char *hex_read_file(const char *filename) { - FILE *file = fopen(filename, "r"); // Open file in read mode + FILE *file = fopen(filename, "r"); if (file == NULL) { hex_error("Failed to open file"); return NULL; } - // Move file pointer to the end to determine the file size - fseek(file, 0, SEEK_END); - long fileSize = ftell(file); - rewind(file); // Reset the file pointer to the beginning - - if (fileSize < 0) + // Allocate an initial buffer + size_t bufferSize = 1024; // Start with a 1 KB buffer + char *content = (char *)malloc(bufferSize); + if (content == NULL) { - hex_error("Failed to determine file size"); + hex_error("Memory allocation failed"); fclose(file); return NULL; } - // Allocate memory for the file content, plus 1 byte for the null terminator - char *content = (char *)malloc(fileSize + 1); - if (content == NULL) + size_t bytesReadTotal = 0; + size_t bytesRead = 0; + + while ((bytesRead = fread(content + bytesReadTotal, 1, bufferSize - bytesReadTotal, file)) > 0) { - hex_error("Memory allocation failed"); + bytesReadTotal += bytesRead; + + // Resize the buffer if necessary + if (bytesReadTotal == bufferSize) + { + bufferSize *= 2; // Double the buffer size + char *temp = (char *)realloc(content, bufferSize); + if (temp == NULL) + { + hex_error("Memory reallocation failed"); + free(content); + fclose(file); + return NULL; + } + content = temp; + } + } + + if (ferror(file)) + { + hex_error("Error reading the file"); + free(content); fclose(file); return NULL; } - // Read the file content into the buffer - size_t bytesRead = fread(content, 1, fileSize, file); - content[bytesRead] = '\0'; // Null-terminate the string - fclose(file); // Close the file + // Null-terminate the content + char *finalContent = (char *)realloc(content, bytesReadTotal + 1); + if (finalContent == NULL) + { + hex_error("Final memory allocation failed"); + free(content); + fclose(file); + return NULL; + } + content = finalContent; + content[bytesReadTotal] = '\0'; + fclose(file); return content; }
M tests.hextests.hex

@@ -15,7 +15,11 @@ )

if ) "test" store -(0x1 "a1" store a1 0x1 == "a1" free) test i -(0x1 0x2 ==) test i +; --- Tests +(0x1 "a" store a 0x1 ==) test i +; --- Report "\nSuccessful Tests: " print successes dec print "/" print successes failures + dec puts + +; --- Cleanup +"a" free