【问题标题】:Run program from c++ source which required multiple input从需要多个输入的 c++ 源代码运行程序
【发布时间】:2014-02-24 14:11:16
【问题描述】:

我需要从 c++ 代码运行 RNAeval(可执行文件)并读取 RNAeval 的输出。我找到了一个可以运行命令并读取输出的代码。

string exec(char* cmd) {
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
    return result;
}

但是RNAeval 不接受任何命令行参数。相反,我需要在运行程序后提供输入(类似于 linux 中的bc)。

示例

RNAeval [enter]
input1 [enter]
input2 [enter]
return output by RNAeval and exit

我如何在 c++ 中做到这一点?

系统:

Linux
g++
gcc

编辑

string exec(char* cmd) {
    FILE* pipe = popen(cmd, "w");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    fprintf(pipe,"%s\n","acgt");
    fprintf(pipe,"%s\n","(())");
    fprintf(pipe,"%s\n","@");
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    } 
    pclose(pipe);
    return result;

}

【问题讨论】:

  • 您可以使用 echo "command\ncommand2" |如果你使用 *nix 系统,程序作为你的参数。
  • 它不起作用(input1\input2)。它不需要命令行参数。

标签: c++ interactive


【解决方案1】:

popen 返回一个 FILE 对象,您可以使用它来编写 RNAEval 的输入流。您可以在执行 popen 后使用 fprintf 向进程写入命令,然后读取结果。

【讨论】:

  • 它有效,但另一个问题。现在程序不会终止。结果正确返回,但不会终止。当我使用“r”标志时,它会成功终止。
  • 看来您只能使用 popen 读写。没有读写。看看这个stackoverflow.com/questions/6171552/…,它可能有适合你的解决方案。
猜你喜欢
  • 1970-01-01
  • 2011-06-24
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多