Sbardila
Sbardila

Reputation: 113

Grab output of stdout with popen line by line in C

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;
}

Upvotes: 1

Views: 1539

Answers (2)

Shawn
Shawn

Reputation: 52344

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;
}

Upvotes: 2

Kurt Weber
Kurt Weber

Reputation: 176

fgetc() is what you want. You'd create a buffer (either statically- or dynamically-allocated), loop over fgetc() and test the value--if it's not a newline, add it to the buffer, if it's a newline, add it to the buffer if that's what you want and then also printf() the buffer, then clear the buffer and continue with the loop.

Upvotes: 1

Related Questions