Reading file of unknown size in C
(November 17, 2019)
reg bufferSize = 1024;
u8 *buffer = malloc(bufferSize); // 1kb buffer
reg readTotal = 0;
while (1) {
reg read = fread(file, &buffer[readTotal], bufferSize - readTotal);
if (read <= 0) {
break; // exit reading loop when done
}
readTotal += read;
if (readTotal >= bufferSize) { // if overflow
bufferSize *= 2; // grow buffer
u8 *bufferNew = realloc(buffer, bufferSize);
if (bufferNew) {
buffer = bufferNew;
} else {
// failed to allocate new buffer
free(buffer);
return;
}
}
}
/* (optional) truncate buffer */
if (bufferSize > readTotal) {
buffer = realloc(buffer, readTotal);
}
|