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++。