Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pipe data to external program using popen
02-02-2010, 08:30 AM (This post was last modified: 02-02-2010 08:37 AM by codecaine.)
Post: #1
Pipe data to external program using popen
What this program do is send my array of strings to the sort progarm in linux or unix base system. The result is that my array is printed on the screen sorted.

Code:
#include <string>

#define MAXSTRS 5

using namespace std;

int main(void)
{
        int  cntr;
        FILE *pipe_fp;
        string strings[MAXSTRS] = { "echo", "bravo", "alpha",
                                  "charlie", "delta"};

        /* Create one way pipe line with call to popen() */
        if (( pipe_fp = popen("sort", "w")) == NULL)
        {
                perror("popen failed");
                return 1;
        }

        /* Processing loop */
        for(cntr=0; cntr<MAXSTRS; cntr++) {
                fputs(strings[cntr].c_str(), pipe_fp);
                fputc('\n', pipe_fp);
        }

        /* Close the pipe */
        pclose(pipe_fp);
        
        return(0);
}

I modified my first program to show you that you can do multiple pipes. popen("sort | more", "w") just like you do in bash I send data to sort once sort program sorts my data it pipes it to the more program the more program just pauses the screen so you can read all the data and scroll down at your own pace.
Code:
#include <string>

#define MAXSTRS 5

using namespace std;

int main(void)
{
        int  cntr;
        FILE *pipe_fp;
        string strings[MAXSTRS] = { "echo", "bravo", "alpha",
                                  "charlie", "delta"};

        /* Create one way pipe line with call to popen() */
        if (( pipe_fp = popen("sort | more", "w")) == NULL)
        {
                perror("popen failed");
                return 1;
        }

        /* Processing loop */
        for(int x = 0; x < 5; x++)
        for(cntr=0; cntr<MAXSTRS; cntr++) {
                fputs(strings[cntr].c_str(), pipe_fp);
                fputc('\n', pipe_fp);
        }

        /* Close the pipe */
        pclose(pipe_fp);
        
        return(0);
}
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: