我寫的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字符混淆了我後來對字符串做的每一個其他操作(我在評論中提到的子字符串)。
這裏是我所看到的例子:
因爲我是一個C/C++初學者,我想請問我如何能可以捕捉過程輸出和流它建議在其他地方,必要時拆分它。代碼可以是C或C++。
沒有C/C++這樣的語言。事實上,你有'static const int BUFFER_SIZE = 512;'表明你正在編寫C++代碼,因爲這種形式的'const'變量在C中是無用的。' – 2010-10-03 04:04:51
順便說一下,'sizeof(char)'是一個非常醜陋的寫'1'的方式。 – 2010-10-03 04:05:43