Home »
Code Examples »
C Code Examples
C – Read Linux Command Output in a Buffer Code Example
The code for Read Linux Command Output in a Buffer
/* Func : Read_Linux_CmdOutput()
* Parameter1 : Linux command to be executed
* Parameter2 : address of the buffer where output is to be stored
* Desc : Executes the passed command on console
and reads the console output to buff
*/
void Read_Linux_CmdOutput(char* command, char** buf)
{
FILE* fp = NULL;
char* ret = NULL;
size_t len = 0;
fp = popen(command, "r");
if (getline(&ret, &len, fp) < 0) {
fprintf(stderr, "whole line can not be read\n");
strcpy(ret, "");
}
if (!strcmp(ret, "")) {
strcpy(*buf, "");
}
else {
size_t len = strlen(ret);
if (ret[len - 1] == '\n')
ret[--len] = '\0';
strcpy(*buf, ret);
}
free(ret);
pclose(fp);
}
Code by Akshit, on August 03, 2022
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
std::string exec(const char* cmd)
{
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}