【问题标题】:How to save the system(cmd) result in a variable?如何将系统(cmd)结果保存在变量中?
【发布时间】:2021-11-19 08:46:45
【问题描述】:

我有一个函数system(cmd),它执行一个向终端返回两个数字的命令:

977190
977190

如何将这些数字之一分配给要在程序中使用的变量?不管是 char 还是 int 变量。

【问题讨论】:

    标签: c


    【解决方案1】:

    如果posix 是一个选项,您可以从system 切换到popen

    #include <stdio.h>
    #include <stdlib.h>
    
    FILE *popen(const char *, const char *);
    int pclose(FILE *);
    
    int main(void)
    {
        FILE *cmd;
    
        cmd = popen("echo 123", "r");
        if (cmd == NULL)
        {
            perror("popen");
            exit(EXIT_FAILURE);
        }
    
        char result[1024];    
        long number = 0;
    
        if (fgets(result, sizeof(result), cmd))
        {
            number = strtol(result, NULL, 10);
        }
        pclose(cmd);
        printf("%ld\n", number);
        return 0;
    }
    

    输出:

    123
    

    【讨论】:

      猜你喜欢
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 2013-10-17
      • 2016-05-20
      相关资源
      最近更新 更多