如何将系统命令输出存储在变量中?

IIT*_*ian 5 c c++ unix system

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

Joh*_*web 6

一个文件名?是.这当然是可能的,但没有使用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(1);
    }

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

    pclose(fpipe);

    return -1;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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

例如,这是我的 C++ 代码

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main(){
   system("ls -l >> a.text");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这里的重定向标志可以轻松地将该命令的所有输出重定向到 .text 文件中。


cni*_*tar 3

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

FILE *popen(const char *command, const char *type);
Run Code Online (Sandbox Code Playgroud)

所以基本上你运行你的command然后从FILE返回的内容中读取。popen(3) 的工作方式与 system 类似(调用 shell),因此您应该能够使用它运行任何内容。