system calls

Discussion in 'Mac Programming' started by dougphd, May 21, 2016.

  1. dougphd macrumors member

    Apr 28, 2016
    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)
  2. dylanryan macrumors member

    Aug 21, 2011
    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.
  3. cqexbesd macrumors regular

    Jun 4, 2009
  4. dougphd thread starter macrumors member

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

    Aug 21, 2011
    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.)

        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)
    After that, out will have something like

         140 someFile.txt
    in it. From there, you can parse it however you want.

Share This Page

4 May 21, 2016