diff options
author | 諏訪子 <suwako@076.moe> | 2024-06-19 23:52:56 +0900 |
---|---|---|
committer | 諏訪子 <suwako@076.moe> | 2024-06-19 23:52:56 +0900 |
commit | b6e3f6cb5d1051777c35988f201e6730525e3389 (patch) | |
tree | 98679f1995f7b103f3314ce54fdf0d1c76df6dbd /src/common.c | |
parent | 8f378429801162d690dc68c0f15b483c1d291838 (diff) |
掃除
Diffstat (limited to 'src/common.c')
-rw-r--r-- | src/common.c | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/src/common.c b/src/common.c new file mode 100644 index 0000000..acb0a45 --- /dev/null +++ b/src/common.c @@ -0,0 +1,60 @@ +#include "common.h" + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +long long int run_command_lld(const char *command) { + char buf[128]; + long long int res = 0; + + FILE *p = popen(command, "r"); + if (!p) { + fprintf(stderr, "コマンドを実効に失敗: %s", command); + return 0; + } + + while (fgets(buf, sizeof(buf), p) != NULL) { + buf[strcspn(buf, "\n")] = '\0'; + } + + res = atoll(buf); + pclose(p); + + return res; +} + +const char *run_command_s(const char *command) { + char buf[128]; + char *out = NULL; + size_t outsize = 0; + + FILE *p = popen(command, "r"); + if (!p) { + fprintf(stderr, "コマンドを実効に失敗: %s", command); + return NULL; + } + + while (fgets(buf, sizeof(buf), p) != NULL) { + buf[strcspn(buf, "\n")] = '\0'; + + size_t len = strlen(buf); + char *nout = realloc(out, outsize + len + 1); + if (nout == NULL) { + perror("メモリの役割に失敗"); + free(out); + pclose(p); + return NULL; + } + + out = nout; + + memccpy(out + outsize, buf, sizeof(buf), len); + outsize += len; + out[outsize] = '\0'; + } + + pclose(p); + + return out; +} |