Since it bit too late that someone is answering I would just like to ask are u still in search of ur answer if yes I'm listing code for what u desired below:
As the code is self-explanatory only few thing demand some clarification. The basic idea is that we use execute the different commands in different processes and output of one is fed to another using pipes and redirection (using pipe() and dup2(). U may use freopen() for redirection which is nothing but just the combination of these two only). Next the final output is redirected to a file (otherwise it will be displayed on terminal) which can then be read easily into some variable (here 'result'. Since I don't know how do u want to use this 'result' I've just displayed it back but u can do as u like).
Also u may want to delete the file that stores ur output temporarily (here 'temp'). U can call unlink() to do so (Though I've commented it out for this would require file to be created every time u run the prog. an unneccessary operation but if its necessary to keep data secret or for any other reason u may either name the file '.temp' to hide it or uncomment the unlink()).
If any more elaboration is required let me know. I'll try to dispell ur doubts. U can also get some refernces for it in Unix System Programming by Terrance Chan or Advanced Unix Programming by Stevens