I am using this code to read a file:
char* fs_read_line(FILE* file)
{
if (file == NULL) {
return "CFILEIO: Error while reading the file: Invalid File";
}
long threshold = ftell(file);
fseek(file, 0, SEEK_END);
uint8_t* buffer = calloc(ftell(file)-threshold, sizeof(uint8_t));
if(buffer == NULL)
return;
int8_t _;
fseek(file, threshold, SEEK_SET);
uint32_t ct = 0;
while ((_ = (char)(fgetc(file))) != '\n'
&& _ != '\0' && _ != '\r' && _ != EOF) {
buffer[ct++] = _;
}
buffer = realloc(buffer, sizeof *buffer * (ct + 1));
buffer[ct] = '\0';
return buffer;
}
If the file is too big, I get (heap) overflow errors, probably because I initally allocate the file with the total amount of characters it contains.
an other way I tried to do this is by realloc
the buffer after every iteration, but that's kinda not the approach I want.
Is there any way to dynamicly change the size of the array depending on the the current iteration without always uisng realloc
? or is there an way to determine how long the current line is by using ftell
and fseek
?