Split stdin lines from getline at commas
C
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
/* Read stdin line by line and print each comma-separated field. */
int main(void)
{
char *line = NULL;
size_t capacity = 0;
ssize_t length;
while ((length = getline(&line, &capacity, stdin)) != -1) {
while (length > 0 && (line[length - 1] == '\n' || line[length - 1] == '\r')) {
line[--length] = '\0';
}
char *field = line;
for (char *cursor = line;; cursor++) {
if (*cursor != ',' && *cursor != '\0') {
continue;
}
char saved = *cursor;
*cursor = '\0';
printf("%s\n", field);
if (saved == '\0') break;
field = cursor + 1;
}
}
free(line);
return 0;
}