If I have a file which contains a '\n' on virtually every line, and I use getline() in a while loop to read the content, is this bad practice?
My understanding is that getline() will be called numerous times for each '\n' char reached, and so realloc() will be called each time also. Which seems inefficient?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("Unable to open file: ");
exit(1);
}
char *buffer = NULL;
size_t len = 0;
ssize_t characters;
while ((characters = getline(&buffer, &len, fp)) != -1) {
fputs(buffer, stdout);
}
fclose(fp);
free(buffer);
buffer = NULL;
return 0;
}