user629034
user629034

Reputation: 669

output redirection in Unix and C

I am trying to run a script inside my C program using system() command. Inside main(), I run the script and it returns the results. How can I put the result of the script in some string and check for conditions? I know I can do it with files but was wondering if its possible to put the result into a string.

Sample would be like:

main()
{
  system("my_script_sh"); // How can I get the result of the my_script_sh
}

Upvotes: 0

Views: 216

Answers (3)

Marc Abramowitz
Marc Abramowitz

Reputation: 3577

Well the easiest thing to do would be to take system("my_script_sh") out of your program and invoke the program from the shell with a pipe -- e.g.: my_script_sh | ./your_c_program and then your C program just reads from stdin (file descriptor 0).

If that is not possible, then have a look at man 3 popen. Basically, you use popen instead of system and it gives you a file handle that you can read from to get the output of the program.

Here are a few links that might be useful:

Upvotes: 0

GWW
GWW

Reputation: 44093

You can't use the system command for that. The best thing to do is use popen:

  FILE *stream;
  char buffer[150];    
  stream = popen("ls", "r");
  while ( fgets(buffer, 150, stream) != NULL ){
      // Copy the buffer to your output string etc.
  }

  pclose(stream);

Upvotes: 5

Alex Reynolds
Alex Reynolds

Reputation: 96927

Use popen() and read the stream into a char * buffer.

Upvotes: 0

Related Questions