Added an option to read input from a file.
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
#include "futil.h"
|
||||
|
||||
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"); //Always open the file in binary mode.
|
||||
|
||||
if (!file) {
|
||||
fprintf(stderr, "Failed to open '%s'. %s.\n", path, strerror(errno));
|
||||
return 0;
|
||||
}
|
||||
|
||||
char *content = NULL, *temp;
|
||||
size_t used = 0, capacity = 0, read = 0; //Allows initialize stack allocated values to zero!
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user