I need to make read lines from a file but i'm do not know how long a line would be. So far the only thing i could think of was to use fgetc and realloc
FILE* cFile = fopen(filename, "r");
....
//some while cycle for going from line to line
....
//now for reading the line itself
char* line = malloc(sizeof(char)); //one empty spot for the '\n'
unsigned int = 0;
char c = getc(cFile);
while (c != '\n') {
line[i] = c;
line = realloc(line, (i+2)*(sizeof(char));
i++;
c = getc(cfile);
}
line[i] = c;
I omnited all the checks for EOL or whether i really got the allocated memory, this is just an example.
My question is, is there any more efficient method of getting a line of unknown length ?
line[0] = c;should beline[i] = c;.line[i] = c;should beline[i] = '\0';buf = malloc(1024*1204);is not memory inefficient. Real memory is allocated when it is used, not necessarily when*alloc()is called.