Skip to content

Instantly share code, notes, and snippets.

@marcelofern
Created May 30, 2021 05:05
Show Gist options
  • Save marcelofern/33564f4934a0b411772e0a8386480bce to your computer and use it in GitHub Desktop.
Save marcelofern/33564f4934a0b411772e0a8386480bce to your computer and use it in GitHub Desktop.
Command line output reader
#define _POSIX_C_SOURCE 2 // to allow popen and pclose.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct cl_reading {
char **output;
int malloc_error;
int n_lines;
int pclose_error;
int popen_error;
int realloc_error;
};
void free_cl_reading(struct cl_reading *reading)
{
for (int i = 0; i < reading->n_lines; i++)
free(reading->output[i]);
free(reading->output);
free(reading);
}
struct cl_reading *read_cl_output(char *cmd, unsigned int max_lines, unsigned int max_line_len)
{
struct cl_reading *reading = malloc(sizeof(*reading));
FILE *fp;
char buf[max_line_len];
unsigned int n_lines = 0;
int pclose_status;
reading->output = malloc(sizeof(*reading->output));
fp = popen(cmd, "r");
if (fp == NULL) {
reading->popen_error = 1;
return reading;
}
while (fgets(buf, max_line_len + 1, fp) && n_lines < max_lines) {
if (*buf == '\n') {
// for when max_line_len < line to be printed.
continue;
}
reading->output[n_lines] = malloc(sizeof(buf));
if (reading->output[n_lines] == NULL) {
reading->malloc_error = 1;
return reading;
}
// trims out the new line character
buf[strcspn(buf, "\n")] = 0;
strcpy(reading->output[n_lines++], buf);
reading->output = realloc(reading->output, (n_lines + 1) * sizeof(*reading->output));
if (reading->output == NULL) {
reading->realloc_error = 1;
return reading;
}
}
pclose_status = pclose(fp);
if (pclose_status == -1) {
reading->pclose_error = 1;
return reading;
}
reading->n_lines = n_lines;
return reading;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment