Help with command substitution in C program

Hi,

I want to know if there's a cleaner way for assigning output of a unix command to a variable in C program .

Example : I execute dirname fname and want the output to be assigned to a variable dname . Is it possible .

I knew u can redirect the output to a file and then reread assigning it , but ca it be done in a leaner better way . Thanks in advance . :o

See man popen. You can read the output from a program without the temporary file in between.

Yes i am aware of popen , but something else which mimics exactly command-substitution (``) of shell ?? How is it achieved in shell ??

It's achieved in the shell by using a shell. C isn't a shell, and a file really isn't a variable, you often don't know how long it is... You have to convert yourself and worry about any special cases yourself.

So write function. Quick and dirty:

size_t get_string(char *buf, size_t max, const char *cmdline)
{
        size_t pos=0;
        FILE *fp=popen(cmdline, "r");
        if(fp == NULL) return(-1);

        while((!feof(fp)) && (pos < (max-1)))
        {
                size_t n=fread(buf+pos, 1, max-(pos+1), fp);
                if(n <= 0) break;
                pos += n;
        }

        buf[pos++]='\0';
        pclose(fp);
        return(pos);
}

int main(void)
{
        char buf[512];
        size_t len=get_string(buf, 512, "echo asdf");

        if(len >= 0)
        {
                printf("string is %s\n", buf);
        }
}
1 Like

popen("command, "r") with fgets() is really the C moral equivalent of somevariable=`command`

what somevariable=` ` does in pseudoC

open FILE *in
fork new child & wait
run 
    exec bin/sh -c commandstring  1> FILE *in
    exit
end new child
read *in > somevariable

This is what popen does as well. The same idea can be done with pipes for 2-way chat between the parent & the child.

system() writes directly to stdout & stderr. popen writes to a file descriptor.

1 Like

Thank you guys .. its clear now ... thanks corona for the "dirty little" function it gave an template to work upon . mcnamara thanks for the cute little code emphasizing the entire point quite shortly .