pipes and the sort command

Jack Jansen jack at vu44.UUCP
Thu Dec 27 21:31:03 AEST 1984


> 	I am interested in using the popen() command to form a pipe
> 	between my C program and the UNIX sort command. I would appreciate
> 	any information on the best way to do this(examples would help).
> 	I should point out that the input to the sort command would be
> 	comming from an array and the output should be stored in an array.
It is very hard to get *both* ends of a pipe into your hands.
The simplest solution is to use a tempfile, which makes your
code something like

    char command[BUFSIZ], *tnm;
    FILE *tfp;
    tnm = tempname();	/* Get temp filename */
    if((tfp = fopen(tnm,"w"))==NULL) <error handling>;
    write_array_to_file(data,tfp);
    fclose(tfp);
    sprintf(command,"sort %s",tnm);
    if( (tfp=popen(command,"r")) == NULL ) <error handling>;
    read_array_from_file(data,tfp);
    if(pclose(tfp) != 0 ) <error handling>; 

In this case, read_array_from_file() and write_array_to_file()
read/write an array to a file (in ASCII), probably with a printf or
scanf loop.

If you don't want to use a tempfile, you have to do it yourself.
This means setting up two pipes, forking, re-directing all file-
descriptors, etc etc etc.
-- 
	Jack Jansen, {seismo|philabs|decvax}!mcvax!vu44!jack
	or				       ...!vu44!htsa!jack
If *this* is my opinion, I wasn't sober at the time.



More information about the Comp.lang.c mailing list