Files
assm-test/src/futil.c
T

58 lines
1.4 KiB
C

#include "../includes/futil.h"
#include <stdio.h>
//Reference: https://stackoverflow.com/a/44894946
int ReadAllString(const char* path, char** content_ptr, size_t* bytes_read) {
if (!path || !content_ptr || !bytes_read) return 0;
FILE *file = fopen(path, "rb");
if (!file) {
fprintf(stderr, "Failed to open '%s'. %s.\n", path, strerror(errno));
return 0;
}
char *content = NULL, *temp = NULL;
size_t used = 0, capacity = 0, read = 0;
while(1) {
if (used + FUTIL_READ_SIZE + 1 > capacity) {
capacity = used + FUTIL_READ_SIZE + 1;
temp = realloc(content, capacity);
if (!temp) {
fprintf(stderr, "Failed to realloc space for file contents. %s.\n", strerror(errno));
free(content);
fclose(file);
return 0;
}
content = temp;
}
read = fread(content + used, 1, FUTIL_READ_SIZE, file);
if (read == 0) break;
used += read;
}
fclose(file);
//Shrink the buffer to fit just the contents of the buffer.
temp = realloc(content, used + 1);
if (!temp) {
fprintf(stderr, "Failed to realloc to only hold the file contents. %s.\n", strerror(errno));
free(content);
return 0;
}
content = temp;
content[used] = '\0';
*content_ptr = content;
*bytes_read = used;
return 1;
}