2015-05-01 125 views
-2

我們得到兩個不同的C++程序的返回值,我有兩個方案A和B計劃A使用system()執行程序B.如何使用Visual Studio 2005

但是,該計劃B使用書面文件方式返回其執行結果。

程序A是獲得程序B返回值的更好方法嗎?

例如

在節目A

int main(){ 
    system("B.exe"); 
    readFile(finePath); 
    //do something 
    return 0; 
} 

在節目B

int main(){ 
    char temp[1024]; 
    //do something 
    writeFile(temp); 
    return 0; 
} 
+0

向我們展示您嘗試過的(簡約代碼)。 – kebs

+0

查看http://stackoverflow.com/questions/3470215/what-is-the-preferred-way-of-passing-data-between-two-applications-on-the-same-s - 也許你會發現一些那裏有用的信息 – 4386427

+1

術語「返回值」對我來說有點混亂,所以只是爲了確保。你沒有詢問程序B的「狀態碼」,對嗎?問題是要獲得B產生的各種結果/輸出,是否正確?導致「狀態碼」通常由system()直接返回。請參閱http://www.cplusplus.com/reference/cstdlib/system/ – 4386427

回答

-1

方法1.

嘗試使用ERRORLEVEL系統變量來檢查返回值任何正在運行的pro公克。

注:
ERRORLEVEL是一個系統變量,因此用它作爲such ...;)

方法2:

可以使用Process.ExitCode屬性。

0

管道是一種相對簡單的跨平臺方式,它不需要在整個地方創建臨時文件,也不必處理由此產生的其他問題。

static string pcommand(const string& cmd) 
{ 
    FILE* stream = _popen(cmd.c_str(), "r"); 
    string data; 
    if (stream) 
    { 
     while (!feof(stream)) 
     { 
      const int buffer_size = 256; 
      char buffer[buffer_size]; 
      if (fgets(buffer, buffer_size, stream)) 
       data.append(buffer); 
     } 
     _pclose(stream); 
    } 
    return data; 
} 

int main() 
{ 
    string 'str' = pcommand("dir"); 
    // 'str' now contains the results sent to stdout 
} 
+0

_popen在Windows上工作嗎? – immibis

+0

是的:https://msdn.microsoft.com/en-us/library/96ayss4b.aspx。我通常在其他平臺上考慮,你可以避免使用下劃線前綴。 –