0

I have code that looks like this:

        char* buff = malloc(strlen(argv[1])+200);

        if (!buff)
        {
            printf("%s\n", "Error allocating memory!");
            return -1;
        }

        sprintf(buff, "%s%s%s%s", "gcc ", argv[1], " -o ", findChars(argv[1], '.'));

        FILE* command = popen(buff, "r");

        // NEED TO RETRIEVE OUTPUT OF POPEN

        pclose(command);

And this works, but I need to save the output of the POPEN to a char* so I can read it. (This is in C)

Chris
  • 154
  • 8

1 Answers1

2

An open pipe is just a FILE*, so any function that can read from a FILE* can do this. For example:

fgets(some_buffer, sizeof(some_buffer), command);

Error handling, repeated reads in case the buffer is too small, all the usual stuff about reading files in C also applies here.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 1
    Thanks so much! This works like a charm. The only question is, how would I allocate enough memory (how ever much memory my command's output is) to my buffer where it's being saved to prevent a buffer overflow? Apart from that tysm :) – Chris Nov 20 '21 at 09:19
  • Again, [any question](https://stackoverflow.com/questions/3747086/reading-the-whole-text-file-into-a-char-array-in-c) about reading files also applies here. – Thomas Nov 20 '21 at 09:48