Can you review below code for performance and stability considerations? It is supposed to take a filename or NULL
. If it is a filename, read given file into memory. If it is NULL
, read from stdin
into memory.
struct file_data {
char *data;
size_t numChars;
};
/* Read whole file into memory */
struct file_data read_file(char *filename) {
FILE *f;
char buffer[BUFFER_SIZE];
char *data = NULL;
size_t current_size = 0;
size_t totalChars = 0;
size_t nchars;
if(filename) {
f = fopen(filename, "r");
} else {
f = stdin;
}
do {
data = (char *)realloc(data, current_size + BUFFER_SIZE);
assert(data);
current_size+=BUFFER_SIZE;
nchars = fread(buffer, 1, BUFFER_SIZE, f);
memcpy(&data[totalChars], buffer, nchars);
totalChars+=nchars;
} while(nchars == BUFFER_SIZE);
struct file_data fd = {data, totalChars};
return fd;
}