Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same program?

UPDATE: Good call on the lack of information. The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux. Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).

like image 639
Josh Matthews Avatar asked Sep 04 '08 03:09

Josh Matthews


People also ask

Can a program be invoked from another program?

As I know, any address in a program only belongs itself, meaning that you can't invoke a function of another program thought its address. Data is code, code is data. As soon as your exploit payload (i.e. machine code) is read into memory by the process you're attacking, it has an address in the target process.

How can I invoke another program from within AC program?

use "system" a in-built function. Say you want to invoke another C program with name abc.exe. system("abc.exe"); // provide absolute path if exe place at other directory.


2 Answers

As others have pointed out, popen() is the most standard way. And since no answer provided an example using this method, here it goes:

#include <stdio.h>  #define BUFSIZE 128  int parse_output(void) {     char *cmd = "ls -l";              char buf[BUFSIZE];     FILE *fp;      if ((fp = popen(cmd, "r")) == NULL) {         printf("Error opening pipe!\n");         return -1;     }      while (fgets(buf, BUFSIZE, fp) != NULL) {         // Do whatever you want here...         printf("OUTPUT: %s", buf);     }      if (pclose(fp)) {         printf("Command not found or exited with error status\n");         return -1;     }      return 0; } 

Sample output:

OUTPUT: total 16 OUTPUT: -rwxr-xr-x 1 14077 14077 8832 Oct 19 04:32 a.out OUTPUT: -rw-r--r-- 1 14077 14077 1549 Oct 19 04:32 main.c 
like image 172
MestreLion Avatar answered Oct 05 '22 22:10

MestreLion


For simple problems in Unix-ish environments try popen().

From the man page:

The popen() function opens a process by creating a pipe, forking and invoking the shell.

If you use the read mode this is exactly what you asked for. I don't know if it is implemented in Windows.

For more complicated problems you want to look up inter-process communication.

like image 42
dmckee --- ex-moderator kitten Avatar answered Oct 05 '22 23:10

dmckee --- ex-moderator kitten