|
Post by ZF on Sept 30, 2009 4:49:03 GMT -5
Taken from: crasseux.com/books/ctutorial/Programming-with-pipes.htmlThe following program example shows how to pipe the output of the ps -A command to the grep init command, exactly as in the GNU/Linux command line example above. The output of this program should be almost exactly the same as sample output shown above. #include <stdio.h> #include <stdlib.h> int main () { FILE *ps_pipe; FILE *grep_pipe; int bytes_read; int nbytes = 100; char *my_string; /* Open our two pipes */ ps_pipe = popen ("ps -A", "r"); grep_pipe = popen ("grep init", "w"); /* Check that pipes are non-null, therefore open */ if ((!ps_pipe) || (!grep_pipe)) { fprintf (stderr, "One or both pipes failed.\n"); return EXIT_FAILURE; } /* Read from ps_pipe until two newlines */ my_string = (char *) malloc (nbytes + 1); bytes_read = getdelim (&my_string, &nbytes, "\n\n", ps_pipe); /* Close ps_pipe, checking for errors */ if (pclose (ps_pipe) != 0) { fprintf (stderr, "Could not run 'ps', or other error.\n"); } /* Send output of 'ps -A' to 'grep init', with two newlines */ fprintf (grep_pipe, "%s\n\n", my_string); /* Close grep_pipe, cehcking for errors */ if (pclose (grep_pipe) != 0) { fprintf (stderr, "Could not run 'grep', or other error.\n"); } /* Exit! */ return 0; }
|
|
|
Post by ZF on Oct 6, 2009 1:14:00 GMT -5
To extract the fields, you can either use awk '{print $4}' or you can use strtok.
<source language="c++"> /* strtok example */ #include <stdio.h> #include <string.h>
int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," ,.-"); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " ,.-"); } return 0; } </source>
|
|