C ++ system () function - How to collect output from issued command?

I run some commands using a C ++ function system():

int system ( const char * command );

How can I get standard output from issued commands?

To be specific, I want to get the result of the issued command (for example, a list of directories output from the command dir).

+3
source share
8 answers

Are you looking for the return value (as in the "exit status") of the executed command or for its output (as in "what it printed")?

If the latter, use popen()and pclose()instead.

, system() ( waitpid() ).

+14

system() int, : int rvalue = system(command);

, , system() , .

+7

"" : stdout . ( , , , , ).

system.

, , popen.

+3

system ( ) , POSIX ( Linux ..) , wait - 8 16 - (, ", " ), , , . URL- man-, , , !

, " " , , ; , , , , popen system.

+3

bmorin, , char * char *, ...

// 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;
}

bmorin, , . , . ( bmorin , stdout, , , () , , char *, . , , .)

+2

system() libc. , , man system .

+1

popen(), , . popen() , POSIX API. API, WIN32

0

( C), popen :

char* exec(const char* command) {
    FILE* fp;
    char* result = NULL;
    size_t len = 0;

    fflush(NULL);
    fp = popen(command, "r");
    if (fp == NULL) {
        printf("Cannot execute command:\n%s\n", command);
        return;
    }

    while(getline(&result, &len, fp) != -1) {
        fputs(result, stdout);
    }

    free(result);
    fflush(fp);
    if (pclose(fp) != 0) {
        perror("Cannot close stream.\n");
    }
    return result;
}
0

Source: https://habr.com/ru/post/1720373/


All Articles