【问题标题】:How to store the system command output in a variable?如何将系统命令输出存储在变量中?
【发布时间】:2011-08-20 15:34:40
【问题描述】:

我正在执行一个 system() 函数,它返回一个文件名。现在我不想在屏幕上显示输出(即文件名)或管道到新文件。我只想将它存储在一个变量中。那可能吗?如果是这样,如何? 谢谢

【问题讨论】:

标签: c++ c unix system


【解决方案1】:

单个文件名?是的。这当然是可能的,但不能使用system()

使用popen()。这在 中可用,您已经用两者标记了您的问题,但可能会在其中一个或另一个中编写代码。

这是一个 C 语言示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *fpipe;
    char *command = "ls";
    char c = 0;

    if (0 == (fpipe = (FILE*)popen(command, "r")))
    {
        perror("popen() failed.");
        exit(EXIT_FAILURE);
    }

    while (fread(&c, sizeof c, 1, fpipe))
    {
        printf("%c", c);
    }

    pclose(fpipe);

    return EXIT_SUCCESS;
}

【讨论】:

  • 这将在printf 调用中导致未定义的行为,因为fread() 不会空终止存储在line 中的字符串。
  • 谢谢,@MarkLakata。我已经解决了这个问题。
  • fread 参数顺序错误。交换第二个和第三个参数。它不会正常工作。
  • @vicky:感谢您强调这不适用于 256 个字符以下的输出。固定。
  • 为什么最后返回-1? -1 表示失败。
【解决方案2】:

您可以使用 popen(3) 并从该文件中读取。

FILE *popen(const char *command, const char *type);

所以基本上你运行你的command,然后从返回的FILE 中读取。 popen(3) 就像 system 一样工作(调用 shell),所以你应该可以用它运行任何东西。

【讨论】:

    【解决方案3】:

    这是我的 C++ 实现,它将system() stdout 重定向到日志系统。它使用 GNU libc 的getline()。如果无法运行命令,它将抛出异常,但如果命令以非零状态运行,则不会抛出异常。

    void infoLogger(const std::string& line); // DIY logger.
    
    
    int LoggedSystem(const string& prefix, const string& cmd)
    {
        infoLogger(cmd);
        FILE* fpipe = popen(cmd.c_str(), "r");
        if (fpipe == NULL)
            throw std::runtime_error(string("Can't run ") + cmd);
        char* lineptr;
        size_t n;
        ssize_t s;
        do {
            lineptr = NULL;
            s = getline(&lineptr, &n, fpipe);
            if (s > 0 && lineptr != NULL) {
                if (lineptr[s - 1] == '\n')
                    lineptr[--s  ] = 0;
                if (lineptr[s - 1] == '\r')
                    lineptr[--s  ] = 0;
                infoLogger(prefix + lineptr);
            }
            if (lineptr != NULL)
                free(lineptr);
        } while (s > 0);
        int status = pclose(fpipe);
        infoLogger(String::Format("Status:%d", status));
        return status;
    }
    

    【讨论】:

      【解决方案4】:

      好吧,还有一种更简单的方法可以将命令输出存储在称为重定向方法的文件中。我认为重定向非常简单,并且对您的情况很有用。

      所以例如这是我在 c++ 中的代码

      #include <iostream>
      #include <cstdlib>
      #include <string>
      using namespace std;
      
      int main(){
         system("ls -l >> a.text");
        return 0;
      }
      

      这里的重定向标志很容易将该命令的所有输出重定向到一个.text文件中。

      【讨论】:

        猜你喜欢
        • 2012-06-21
        • 2011-04-20
        • 1970-01-01
        • 1970-01-01
        • 2010-12-29
        • 2012-07-19
        • 2014-10-21
        • 2015-03-10
        • 1970-01-01
        相关资源
        最近更新 更多