Stream a text file line by line with getline in C
C
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_lines(const char *path, int (*visit)(char *, void *), void *ctx) {
FILE *f = fopen(path, "r");
if (!f) return -1;
char *line = NULL;
size_t cap = 0;
int total = 0;
while (getline(&line, &cap, f) > 0) {
line[strcspn(line, "\r\n")] = '\0';
total += visit(line, ctx);
}
free(line);
fclose(f);
return total;
}