OEOE.MOE

[ frontpage ]
about / projects / useful things / not very useful things
page #1 (ptl, dda) page #2 (tri) page #3 (grd, dth) page #4 (3d) page #5 (buf) page #6 (idx) scratches

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);
}