I am writing C / C++ code to run a shell command and capture the output:
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
}
It's working with a glitch: I see that the buffer contain some non-ascii chars at the end that are messing up every other operation I do with the string afterwards (the substring I mentioned on the comment).
Here's an example of what I am seeing:
Since I am a C / C++ beginner, I'd like to ask advice on how can I can capture the process output and stream it somewhere else, splitting it when necessary. The code can be in C or C++.