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
}
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);
使用popen()
并将流读入char *
缓冲区。
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 -- eg: my_script_sh | ./your_c_program
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.