2010-10-03 13 views
2

我寫的C/C++代碼運行shell命令並捕獲輸出:正確正從一個在C管輸出/ C++

static const int BUFFER_SIZE=512; 

// (...) 

FILE* pipe; 
char buffer[BUFFER_SIZE]; 

// (...) 

if (!(pipe = popen(cmd.c_str(), "r"))) { 
    out("\nProblem executing command: " + cmd + "\n"); 
    return 1; 
} 

while (!feof(pipe)) { 
    int read = fread(buffer, sizeof(char), sizeof buffer, pipe); 
    int pos = -1; 
    int i; 

    for (i = 0; i < strlen(buffer); i++) { 
    if (buffer[i] == '\n') { 
     pos = i; 
    } 
    } 

    // ... get a substring from buffer var from 0 to pos, 
    // and set a "reminder" var with pos+1 to end of string 
} 

它的工作有一個小故障:我看到的是,緩衝區包含一些最後的非ASCII字符混淆了我後來對字符串做的每一個其他操作(我在評論中提到的子字符串)。

這裏是我所看到的例子:

Error example

因爲我是一個C/C++初學者,我想請問我如何能可以捕捉過程輸出和流它建議在其他地方,必要時拆分它。代碼可以是C或C++。

+0

沒有C/C++這樣的語言。事實上,你有'static const int BUFFER_SIZE = 512;'表明你正在編寫C++代碼,因爲這種形式的'const'變量在C中是無用的。' – 2010-10-03 04:04:51

+0

順便說一下,'sizeof(char)'是一個非常醜陋的寫'1'的方式。 – 2010-10-03 04:05:43

回答

1

fread不會NUL終止緩衝區,所以strlen是不合適的。

使用結果read來限制您的循環。

+0

小心編寫一些(元)代碼,以便我能理解? – kolrie 2010-10-03 03:44:42

+0

沒關係!我知道了。 – kolrie 2010-10-03 03:46:04