153

Possible Duplicate:
How can I run an external program from C and parse its output?

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. Is there a more elegant way than making a temporary file?

Community
  • 1
  • 1
jimi hendrix
  • 2,051
  • 5
  • 18
  • 18

2 Answers2

282

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;
  char path[1035];

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

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

  /* close */
  pclose(fp);

  return 0;
}
Matt K
  • 6,287
  • 3
  • 35
  • 53
  • 1
    Redirecting stderr to stdout may be a good idea, so you catch errors. –  Mar 14 '09 at 17:12
  • how would i redirect stderr to stdout? – jimi hendrix Mar 14 '09 at 21:06
  • 12
    you should use `fgets(path, sizeof(path), fp)` not `sizeof(path)-1`. read the manual – user102008 Dec 22 '10 at 00:25
  • 4
    @jimi: You can redirect stderr to stdout in the shell command you're running through popen, e.g. fp = popen("/bin/ls /etc/ 2>&1", "r"); – rakslice Apr 05 '11 at 22:25
  • 1
    There seems to be a 2 way communication using popen, if I issue a command that prompts the user for confirmation then I get the prompt. What I can I do if I just want to read the output and if there is prompt then I just exit – Sachin Jul 13 '12 at 18:42
  • Thanks! Very helpful. FYI, it appears that `int status` is not being used. No big deal. EDIT: I removed it. – arr_sea May 08 '13 at 00:51
  • Let's assume there are no files inside /etc/, then what will be stored in path variable? I am asking this because I am planning to run pidOf node instead of ls -l . Let's assume node is not running then pidOf node will return nothing. In such a case, what will return in path variable here? – dexterous Feb 18 '18 at 02:24
  • The buffer will be empty/unset. –  Feb 23 '18 at 04:02
5

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

dirkgently
  • 101,474
  • 16
  • 123
  • 183