I want to read the output of a program line by line and do stuff after each line (terminated by "\n"). The following piece of code reads chunks of 50 chars and prints the output. Is there any way i can read until newline comes?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
FILE* file = popen("some program", "r");
char out[50];
while(fgets(out, sizeof(out), file) != NULL)
{
printf("%s", out);
}
pclose(file);
return 0;
}
You can use getline()
to always read a full line at a time, no matter its length:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
FILE* file = popen("some program", "r"); // You should add error checking here.
char *out = NULL;
size_t outlen = 0;
while (getline(&out, &outlen, file) >= 0)
{
printf("%s", out);
}
pclose(file);
free(out);
return 0;
}