![](/img/trans.png)
[英]c++ issue reading a file with getline() and getting output formatted properly
[英]Properly getting output from a pipe in C / C++
我正在编写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
的结果来限制循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.