How can I run an external program from C and parse its output?

后端 未结 8 962
死守一世寂寞
死守一世寂寞 2020-11-22 04:18

I\'ve got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same pr

8条回答
  •  伪装坚强ぢ
    2020-11-22 04:34

    As others have pointed out, popen() is the most standard way. And since no answer provided an example using this method, here it goes:

    #include 
    
    #define BUFSIZE 128
    
    int parse_output(void) {
        char *cmd = "ls -l";    
    
        char buf[BUFSIZE];
        FILE *fp;
    
        if ((fp = popen(cmd, "r")) == NULL) {
            printf("Error opening pipe!\n");
            return -1;
        }
    
        while (fgets(buf, BUFSIZE, fp) != NULL) {
            // Do whatever you want here...
            printf("OUTPUT: %s", buf);
        }
    
        if(pclose(fp))  {
            printf("Command not found or exited with error status\n");
            return -1;
        }
    
        return 0;
    }
    

    Sample output:

    OUTPUT: total 16
    OUTPUT: -rwxr-xr-x 1 14077 14077 8832 Oct 19 04:32 a.out
    OUTPUT: -rw-r--r-- 1 14077 14077 1549 Oct 19 04:32 main.c
    

提交回复
热议问题