I wrote this function for my next learning project (cfg parser). What do you think about it?
char readline(FILE *fp, char **line, size_t *size) {
*size = 0;
size_t cpos = ftell(fp);
int c;
while ((c = fgetc(fp)) != '\n' && c != EOF) (*size)++;
if (*size == 0 && c == EOF) {
*line = NULL;
return 1;
}
*line = calloc(*size + 1, sizeof(char));
if (*line == NULL)
return -1;
fseek(fp, cpos, SEEK_SET);
if (fread(*line, 1, *size, fp) != *size)
return -2;
fgetc(fp); // Skip that newline
return 0;
}
Can be used as follows:
FILE *fp = fopen("file.txt", "rb");
char *line = NULL;
size_t size = 0;
readline(fp, &line, &size);