2010-02-14 25 views
4

可能重複:
How can I run an external program from C and parse its output?如何捕獲來自系統的結果()在C/C++

嗨,

可能有人請告訴我們如何捕捉時的結果執行system()函數?

其實我寫了一個顯示計算機IP地址的C++程序,名爲「ipdisp」,我希望當一個服務器程序執行這個ipdisp程序時,服務器將顯示IP地址。那麼,這可能嗎?如果是的話,怎麼樣?

感謝您的答覆

+0

多次問及回答。一個例子:http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output – dmckee

+0

對不起,我不知道當我寫了這個問題,我沒有看到相關的問題。謝謝! – make

回答

6

是的,你可以這樣做,但你不能使用system(),你將不得不使用popen()代替。例如:

FILE *f = popen("ipdisp", "r"); 
while (!feof(f)) { 
    // ... read lines from f using regular stdio functions 
} 
pclose(f); 
+0

非常感謝!只是爲了澄清請。顯示的變量例如是(char * xx1;)所以我們如何獲得xx1?再次感謝! – make

+0

假設'ipdisp'將其輸出寫入標準輸出,您將可以通過上面的文件'f'讀取其標準輸出。使用'fgets'或類似的。 –

+0

謝謝!其實我有兩個變量:hostname和ipaddress,我想要capte ipaddress。標準輸出是最後顯示的一個嗎?再次感謝 – make

1

Greg不完全正確。你可以使用系統,但這是一個非常糟糕的主意。您可以通過將命令的輸出寫入臨時文件然後讀取文件來使用系統......但popen()是一種更好的方法。例如:

 
#include <stdlib.h> 
#include <stdio.h> 
void 
die(char *msg) { 
    perror(msg); 
    exit(EXIT_FAILURE); 
} 

int 
main(void) 
{ 
    size_t len; 
    FILE *f; 
    int c; 
    char *buf; 
    char *cmd = "echo foo"; 
    char *path = "/tmp/output"; /* Should really use mkstemp() */ 

    len = (size_t) snprintf(buf, 0, "%s > %s", cmd, path) + 1; 
    buf = malloc(len); 
    if(buf == NULL) die("malloc"); 
    snprintf(buf, len, "%s > %s", cmd, path); 
    if(system(buf)) die(buf); 
    f = fopen(path, "r"); 
    if(f == NULL) die(path); 
    printf("output of command: %s\n", buf); 
    while((c = getc(f)) != EOF) 
     fputc(c, stdout); 
    return EXIT_SUCCESS; 
} 

有很多的問題,這種方法......(語法重定向的可移植性,使在文件系統中的文件,與其他進程讀取臨時文件的安全性問題,等等,等等。 )