C Function to Run External Command and Capture the Output


In the following C function, we can launch a command and capture its output and store in a 2 dimensional char array. The function returns the number of the lines of the output. Each line is ended with the new line carriage “\n”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#define LINE_MAX_BUFFER_SIZE 255
 
int runExternalCommand(char *cmd, char lines[][LINE_MAX_BUFFER_SIZE]) {
  FILE *fp;
  char path[LINE_MAX_BUFFER_SIZE];
 
  /* Open the command for reading. */
  fp = popen(cmd, "r");
  if (fp == NULL) {
    return -1;
  }
 
  int cnt = 0;
  while (fgets(path, sizeof(path), fp) != NULL) {
    strcpy(lines[cnt++], path);
  }
  pclose(fp);
  return cnt;  
}
#define LINE_MAX_BUFFER_SIZE 255

int runExternalCommand(char *cmd, char lines[][LINE_MAX_BUFFER_SIZE]) {
  FILE *fp;
  char path[LINE_MAX_BUFFER_SIZE];

  /* Open the command for reading. */
  fp = popen(cmd, "r");
  if (fp == NULL) {
    return -1;
  }

  int cnt = 0;
  while (fgets(path, sizeof(path), fp) != NULL) {
    strcpy(lines[cnt++], path);
  }
  pclose(fp);
  return cnt;  
}

In order to use this function, you would need to allocate the **char array in advance. In C, you would usually allocate and deallocate the array in the caller. One example:

1
2
3
4
5
6
7
8
int main() {
    char output[100][LINE_MAX_BUFFER_SIZE];
    int a = runExternalCommand("ls", output);
    for (int i = 0; i < a; ++ i) {
        printf("%s", output[i]);
    }
    return 0;
}
int main() {
    char output[100][LINE_MAX_BUFFER_SIZE];
    int a = runExternalCommand("ls", output);
    for (int i = 0; i < a; ++ i) {
        printf("%s", output[i]);
    }
    return 0;
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
221 words
Last Post: Teaching Kids Programming - Count of Sublists with Same First and Last Values
Next Post: Teaching Kids Programming - ROT13 String Cipher Algorithm in Python

The Permanent URL is: C Function to Run External Command and Capture the Output

Leave a Reply