gpt4 book ai didi

c++ - 从 C++ 程序运行 shell 脚本会自动将 shell 脚本的输出显示到控制台吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:09:35 25 4
gpt4 key购买 nike

我正在上 Linux 类(class),但我以前从未学过 C++。我的 shell 脚本基本上可以自己完成所有事情,但我需要从 c++ 程序中使用它。从命令行运行时我的 shell 脚本输出我想要返回到控制台的结果。当我从 c++ 程序运行它时,我的程序编译并运行但没有输出。这是因为我的 c++ 程序中有一些错误,还是因为 c++ 和 shell 脚本交互的方式而应该发生?

我看到一些关于从 shell 脚本中获取输出并在 c++ 程序中使用它的问题,但我不想那样做。从字面上看,我的所有 C++ 程序所做的就是运行 shell 脚本。

我只想在控制台上显示我的 shell 脚本的输出。你能帮我吗?如果需要,我可以发布我正在使用的代码。

C++:

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main (int argc, char *argv[]) {
string arg;
arg = string(argv[1]);
if (argc >= 2) {
for (int i=2; i < argc; i++) {
string temp = string(argv[i]);
arg=arg+" "+temp;
}
}
string command;
command = "./findName.sh "+ arg;
//cout << command;
system("command");

return 0;
}

最佳答案

如果你想实时显示输出,你可以使用这样的东西:

FILE* outputStream;

char buffer[1024];
outputStream = popen(command,"r");

if (outputStream == NULL)
return 1; //couldn't execute command

while (fgets(buffer, sizeof(buffer), outputStream) != NULL) {
//read output line-by-line to buffer and display it
std::cout << buffer << std::endl;
}

pclose(outputStream);

关于c++ - 从 C++ 程序运行 shell 脚本会自动将 shell 脚本的输出显示到控制台吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21844958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com