C++ system() function — How to collect the output of the issued command?

前端 未结 8 1698
暖寄归人
暖寄归人 2020-12-03 16:14

I\'m running some commands with the C++ system() function:

int system ( const char * command );

How can I collect the standard

8条回答
  •  甜味超标
    2020-12-03 16:57

    Inspired by bmorin's attempt, but working and tested, this snippet will take a char* command and return a char* containing the results of executing that command...

    // Calling function must free the returned result.
    char* exec(const char* command) {
      FILE* fp;
      char* line = NULL;
      // Following initialization is equivalent to char* result = ""; and just
      // initializes result to an empty string, only it works with
      // -Werror=write-strings and is so much less clear.
      char* result = (char*) calloc(1, 1);
      size_t len = 0;
    
      fflush(NULL);
      fp = popen(command, "r");
      if (fp == NULL) {
        printf("Cannot execute command:\n%s\n", command);
        return NULL;
      }
    
      while(getline(&line, &len, fp) != -1) {
        // +1 below to allow room for null terminator.
        result = (char*) realloc(result, strlen(result) + strlen(line) + 1);
        // +1 below so we copy the final null terminator.
        strncpy(result + strlen(result), line, strlen(line) + 1);
        free(line);
        line = NULL;
      }
    
      fflush(fp);
      if (pclose(fp) != 0) {
        perror("Cannot close stream.\n");
      }
      return result;
    }
    

    I looked into just editing bmorin's code, but would have had to change most lines, so a separate answer seemed more appropriate. Apologies if not. (Amongst other problems, bmorin's code didn't actually accumulate the lines; it printed them to stdout, where I presume they would not be wanted, since system() would have done that; and it returned void in one error path, when the function must return a char*, so the code wouldn't compile. Perhaps most egregious, it freed the result just before returning it.)

提交回复
热议问题