Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Invoking Unix shell commands from compiled C

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
This may seem simple (I hope it is) and sound stupid (I feel stupid).

If I want to compile some C code (read: not script in csh or anything else) but invoke shell commands how do I do it?

In other words if I wanted to have a C program where I wanted to complie something like:

#include <stdio.h>
{
x = awk '{print $7}' infile.txt;
printf (&quot;%x is the value\n&quot;);
}


How do I get that value from the shell (using interpreted awk in this case) to x????

I want to write some code and COMPILE it in C, but want to freely use the shell, like in perl or a shell script I would just use ``

But I can't do that in C.

I hope this makes sense, if not please feel free to ask me questions.

Thanks!
 
try
system(&quot;your shell command&quot;); John Fill
ivfmd@mail.md
 
There's more than one way to do it, here are a few common ways:

Use system() and have the shell command write its output into a file and then have your C program open the file and parse the contents:

#include <stdlib.h>

/* ... */

const char command[]=&quot;awk '{print $7}' infile.txt > outfile.txt&quot;;

if (system(command)==0) {
FILE *fp=fopen(&quot;outfile.txt&quot;,&quot;r&quot;);
if (fp!=NULL) {
/* read output of awk command */
}
fclose(fp);
}

Much Better (and faster!): Use popen() (pipe open) which should be available to you:

#include <stdio.h>

/* ... */

const char command[]=&quot;awk '{print $7}' infile.txt&quot;;
FILE *proc;

/* open a pipe to the command */
proc=popen(command,&quot;r&quot;);

if (proc!=NULL) {
/* read proc just like you would any other file,
* possibly using a function like fgets() to read
* the output of the awk command line by line.
*/

pclose(proc);
}

Check your man page for more details.

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top