diff options
Diffstat (limited to 'src/cmd_out.c')
| -rw-r--r-- | src/cmd_out.c | 66 |
1 files changed, 34 insertions, 32 deletions
diff --git a/src/cmd_out.c b/src/cmd_out.c index bc371e0..f2d6bf4 100644 --- a/src/cmd_out.c +++ b/src/cmd_out.c @@ -26,35 +26,37 @@ #include "cmd_out.h" char* cmd_out(const char *cmd) { - FILE *pipe = popen(cmd, "r"); - if (!pipe) return strdup(""); - - char buffer[128]; - size_t total_size = 0; - size_t capacity = 256; - char *result = malloc(capacity); - if (!result) { - pclose(pipe); - return strdup(""); - } - result[0] = '\0'; - - while (fgets(buffer, sizeof(buffer), pipe) != NULL) { - size_t len = strlen(buffer); - if (total_size + len + 1 > capacity) { - capacity *= 2; - char *new_result = realloc(result, capacity); - if (!new_result) { - free(result); - pclose(pipe); - return strdup(""); - } - result = new_result; - } - strcat(result, buffer); - total_size += len; - } - - pclose(pipe); - return result; -}
\ No newline at end of file + FILE *pipe = popen(cmd, "r"); + if (!pipe) return strdup(""); + + char buffer[128]; + size_t total_size = 0; + size_t capacity = 256; + char *result = malloc(capacity); + if (!result) { + pclose(pipe); + return strdup(""); + } + result[0] = '\0'; + + while (fgets(buffer, sizeof(buffer), pipe) != NULL) { + size_t len = strlen(buffer); + // Ensure enough space for the new chunk + 1 byte for '\0' + if (total_size + len + 1 > capacity) { + capacity *= 2; + char *new_result = realloc(result, capacity); + if (!new_result) { + free(result); + pclose(pipe); + return strdup(""); + } + result = new_result; + } + + snprintf(result + total_size, capacity - total_size, "%s", buffer); + total_size += len; + } + + pclose(pipe); + return result; +} |
