我需要从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;
}
最佳答案
popen返回一个FILE对象,可用于编写RNAEval的输入流。执行完popen之后,可以使用fprintf将命令写入进程,然后读入结果。