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”.
#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:
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) —
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