tags:

views:

2914

answers:

4

hi, i want to run a command in linux, and get the text returned of what it outputs...but i DO NOT want this text printed to screen. There has to be a more elegant way than making a temporary file right?

Duplicate of http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output

+2  A: 

You need some sort of Inter Process Communication. Use a pipe or a shared buffer.

dirkgently
+11  A: 

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  int status;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit;
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}


Steve Kemp
Redirecting stderr to stdout may be a good idea, so you catch errors.
Lars Wirzenius
how would i redirect stderr to stdout?
jimi hendrix
A: 

Usually, if the command is an external program, you can use the OS to help you here.

command > file_output.txt

So your C code would be doing something like

exec("command > file_output.txt");

Then you can use the file_output.txt file.

Tommy Hui
The poster did explicitly rule out the use of temporary files, but its a valid approach for some cases. Just make sure you don't use a static filename use a secure random filename or you open yourself to symlink attacks which are security issues..
Steve Kemp
this answer is completely incorrect, because the argument passed to exec isn't a shell command.
Alnitak
+1  A: 

This is a classic:

  1. Create a pipe.
  2. fork();
  3. In the child, configure file descriptors.
  4. exec the command in the child.
Mehrdad Afshari