Line data Source code
1 : #include <stdio.h> 2 : #include <string.h> 3 : #include <stdlib.h> 4 : #include <stdarg.h> 5 : #include <math.h> 6 : #include <sys/types.h> 7 : #include <unistd.h> 8 : #include "util.h" 9 : 10 84 : int str_append(char **dst, const char *format, ...) 11 : { 12 84 : char *str = NULL; 13 84 : char *old_dst = NULL, *new_dst = NULL; 14 : 15 84 : va_list arg_ptr; 16 84 : va_start(arg_ptr, format); 17 84 : vasprintf(&str, format, arg_ptr); 18 84 : va_end(arg_ptr); 19 : 20 : // save old dst 21 84 : asprintf(&old_dst, "%s", (*dst == NULL ? "" : *dst)); 22 : 23 : // calloc new dst memory 24 84 : new_dst = (char *)calloc(strlen(old_dst) + strlen(str) + 1, sizeof(char)); 25 : 26 84 : strcat(new_dst, old_dst); 27 84 : strcat(new_dst, str); 28 : 29 84 : if (*dst) free(*dst); 30 84 : *dst = new_dst; 31 : 32 84 : free(old_dst); 33 84 : free(str); 34 : 35 84 : return 0; 36 : } 37 : 38 84 : char* execute(char* cmd) { 39 84 : char buffer[128]; 40 : 41 84 : char *output = NULL; 42 : 43 : // Open pipe to file 44 84 : FILE* pipe = popen(cmd, "r"); 45 84 : if (!pipe) { 46 : return (char*)"popen failed!"; 47 : } 48 : 49 : // read till end of process: 50 252 : while (!feof(pipe)) { 51 : // use buffer to read and add to result 52 168 : if (fgets(buffer, 128, pipe) != NULL) { 53 84 : str_append(&output, "%s", buffer); 54 : } 55 : } 56 : 57 84 : pclose(pipe); 58 84 : return output; 59 : }