简体   繁体   中英

Save output from (void) system into a variable (C)

Here is my code:

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

int main()
{
(void)system("cat json.json | ./jq.exe '.location | {street, city}'");
return 0;
}

I want to save the output from (void)system into a variable but how exactly would I do that?

You will have to create a pipe and redirect the output from the system call to that pipe, and then read the data from the pipe -- this is what the popen call essentially does, which means that you should just convert the system call to a popen call and then read from the file descriptor into the variables you want to populate.

You can find examples on how to use popen on stack overflow, like this one here; linux command executing by popen on C code

Standard C offers no real solution for this; there are only workarounds. One would be to use shell redirection inside system(), writing the output to a file, then reading that file using fopen() , fread() and friends.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM