我正在编写 C/C++ 代码来运行 shell 命令并捕获输出:
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++。
最佳答案
fread
不会 NUL 终止缓冲区,所以 strlen
是不合适的。
使用结果 read
来限制你的循环。
关于c++ - 在 C/C++ 中正确地从管道获取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3848455/