Help with command substitution in C program


 
Thread Tools Search this Thread
Top Forums UNIX for Advanced & Expert Users Help with command substitution in C program
# 1  
Old 10-17-2010
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 . Smilie
# 2  
Old 10-17-2010
See man popen. You can read the output from a program without the temporary file in between.
# 3  
Old 10-17-2010
Yes i am aware of popen , but something else which mimics exactly command-substitution (``) of shell ?? How is it achieved in shell ??
# 4  
Old 10-18-2010
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:
Code:
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);
        }
}


Last edited by Corona688; 10-18-2010 at 03:15 PM.. Reason: better return value
This User Gave Thanks to Corona688 For This Post:
# 5  
Old 10-18-2010
popen("command, "r") with fgets() is really the C moral equivalent of somevariable=`command`

what somevariable=` ` does in pseudoC
Code:
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.
This User Gave Thanks to jim mcnamara For This Post:
# 6  
Old 10-18-2010
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 .
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Command option substitution?

Hi folks, I totally dislike asking questions in forums but this one eats up to much of my time I need to spend on other topics. I have a shell-script in which I call a terminal. I want to invoke bash inside the terminal and print a message inside bash with aid of a here document. See... (7 Replies)
Discussion started by: bluntroller
7 Replies

2. Shell Programming and Scripting

Regarding command substitution

Oracle Linux 5.6, 64-bit Given the following snippet wrkvar=`sqlplus -s / as sysdba <<EOF set echo off feedback off head off trimsp on select count(*) from v\$parameter where name in ('db_file_name_convert','log_file_name_convert') and value is not null; EOF` echo wrkvar=$wrkvarProduces... (2 Replies)
Discussion started by: edstevens
2 Replies

3. Shell Programming and Scripting

Substitution within string command

I have the following code: strfuture=abcdefghi ver=${strfuture:${count}:1} mj7777_ver=${ver} start_mj7777_iteration let count=count+1 When it is executed I get bad substitution. The same if I use ver=${strfuture:$count:1} mj7777_ver=${ver}... (6 Replies)
Discussion started by: Bruble
6 Replies

4. Shell Programming and Scripting

command substitution doubt

Hi, I almost always use back quotes in scripts to assigin output of a command to a variable. eg: file=`basename a/b/c/d/file` year_mon=`date +%Y%m` But the same can be achieved like: file=$(basename a/b/c/d/file) year_mon=$(date +%Y%m) I would like to know if there is... (3 Replies)
Discussion started by: wanderingmind16
3 Replies

5. UNIX for Dummies Questions & Answers

read command - using output from command substitution

Hey, guys! Trying to research this is such a pain since the read command itself is a common word. Try searching "unix OR linux read command examples" or using the command substitution keyword. :eek: So, I wanted to use a command statement similar to the following. This is kinda taken... (2 Replies)
Discussion started by: ProGrammar
2 Replies

6. UNIX for Dummies Questions & Answers

sed insert command and variable expansion/command substitution

I know this script is crummy, but I was just messing around.. how do I get sed's insert command to allow variable expansion to show the filename? #!/bin/bash filename=`echo $0` /usr/bin/sed '/#include/ { i\ the filename is `$filename` }' $1 exit 0 (8 Replies)
Discussion started by: glev2005
8 Replies

7. Shell Programming and Scripting

Can process substitution be used as an input file to another program?

Hey, I was trying to figure out how to launch a program from the command line, and it works if you pass it a config file. I was thinking about writing a script to dynamically create the config file and pass it to the command using something like command substitution (so I don't actually have to... (3 Replies)
Discussion started by: bj0
3 Replies

8. Shell Programming and Scripting

Difference between "Command substitution" and "Process substitution"

Hi, What is the actual difference between these two? Why the following code works for process substitution and fails for command substitution? while IFS= read -r line; do echo $line; done < <(cat file)executes successfully and display the contents of the file But, while IFS='\n' read -r... (3 Replies)
Discussion started by: royalibrahim
3 Replies

9. UNIX for Dummies Questions & Answers

Script to open program and send/execute command in program

Hi, i want to write a script that executes a program (exec?) . this program then requires a filename as input. how do i give it this input in the script so the program will be complete run and close by the script. e.g. exec prog.exe program then asks for filename "enter filename:"... (1 Reply)
Discussion started by: tuathan
1 Replies

10. Shell Programming and Scripting

Substitution of last command

"Is there any substituation of last command or script syntax which can be used as a user. As far I know the "last" command is being used to display information about previous logins. A member of adm group or the user adm can execute it only. Thanks in advance for your usual help. Ghazi (6 Replies)
Discussion started by: ghazi
6 Replies
Login or Register to Ask a Question