[v1.01] Improve read_file implementation as suggested in #137

This commit is contained in:
Dr-Noob
2022-02-10 22:27:51 +01:00
parent c4b2f31320
commit 316c2dec40

View File

@@ -54,19 +54,18 @@ char* read_file(char* path, int* len) {
//File exists, read it //File exists, read it
int bytes_read = 0; int bytes_read = 0;
int offset = 0; int offset = 0;
int block = 128; int block = 1024;
int buf_size = block * 4; int buf_size = block * 4;
char* buf = emalloc(sizeof(char) * buf_size); char* buf = emalloc(sizeof(char) * buf_size);
memset(buf, 0, sizeof(char) * buf_size);
while ((bytes_read = read(fd, buf+offset, block)) > 0) { while ((bytes_read = read(fd, buf+offset, block)) > 0) {
offset += bytes_read; offset += bytes_read;
if(offset + block > buf_size) { if(offset + block > buf_size) {
buf = erealloc(buf, sizeof(char) * buf_size * 2); buf = erealloc(buf, sizeof(char) * (buf_size + block));
memset(buf + buf_size, 0, sizeof(char) * buf_size); buf_size += block;
buf_size = buf_size * 2;
} }
} }
buf[offset] = '\0';
if (close(fd) == -1) { if (close(fd) == -1) {
return NULL; return NULL;