Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

dougphd

macrumors member
Original poster
Apr 28, 2016
70
0
How do I get the result of a system call in to a c variable. Do I have to write it to a file and then read the file or is there a better way?

system (* > piped to file);
read file;

or system (* > assigned to c variable)
 

dylanryan

macrumors member
Aug 21, 2011
57
2
try popen, which returns a FILE pointer that you can read or write to. (close it with pclose). Similar to using system to write to a file, but without the need of a file.
 

dougphd

macrumors member
Original poster
Apr 28, 2016
70
0
An example: Say the system call is wc -l. How to I get the output into a c variable.
 

dylanryan

macrumors member
Aug 21, 2011
57
2
Did you read the man page for popen?

Here is an example I threw together (with no attempt to do error correction. You'd want to check all the return values to make sure things work, naturally.)

Code:
    char out[1024];
    FILE* wc=popen("wc -c someFile.txt","r"); // calls the command and returns a FILE pointer pointing to its std out
    fgets(out,1024,wc); // read the first line of the output
    pclose(wc); // close the FILE. (note: if the command is long-running, this will wait for it to exit before continuing)
    printf("%s\n",out);

After that, out will have something like

Code:
     140 someFile.txt

in it. From there, you can parse it however you want.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.