2014-02-18 40 views
2

我正在參加一個Linux課程,我從來沒有做過C++。我的shell腳本基本上都是自己做的,但我需要從C++程序中使用它。從命令行運行時,我的shell腳本將我想返回到控制檯的結果輸出。當我從C++程序運行它時,我的程序編譯並運行,但沒有輸出。這是因爲我的C++程序中有一些錯誤,或者這是因爲C++和shell腳本交互的方式而發生的?從C++程序運行shell腳本會自動將shell腳本的輸出顯示給控制檯嗎?

我看到了一些關於從shell腳本中獲取輸出並在C++程序中使用它的問題,但我不想那樣做。從字面上看,我所有的C++程序都是運行shell腳本。

我只想讓我的shell腳本的輸出顯示在控制檯上。你能幫我嗎?如果需要,我可以發佈我正在使用的代碼。

C++:

#include <iostream> 
#include <string> 
#include <stdio.h> 
#include <stdlib.h> 
using namespace std; 

int main (int argc, char *argv[]) { 
    string arg; 
    arg = string(argv[1]); 
    if (argc >= 2) { 
     for (int i=2; i < argc; i++) { 
      string temp = string(argv[i]); 
      arg=arg+" "+temp; 
     } 
    } 
    string command; 
    command = "./findName.sh "+ arg; 
    //cout << command; 
    system("command"); 

    return 0; 
} 
+0

是的,請張貼代碼 – Brian

+0

這很可能是執行shell腳本只是默默地失敗,這就是爲什麼沒有輸出。但是,如果我們看不到您的代碼,沒有人可以肯定地說。 – Brian

+3

它應該是系統(命令);而不是系統(「命令」); – androidFan

回答

0

如果你想顯示的實時輸出,你可以使用這樣的事情:

FILE* outputStream; 

char buffer[1024]; 
outputStream = popen(command,"r"); 

if (outputStream == NULL) 
    return 1; //couldn't execute command 

while (fgets(buffer, sizeof(buffer), outputStream) != NULL) { 
    //read output line-by-line to buffer and display it 
    std::cout << buffer << std::endl; 
} 

pclose(outputStream);