在 Windows 上运行带有 C++ 的 bash 脚本

Run a bash script with C++ on Windows

本文关键字:C++ bash 脚本 行带 Windows 运行      更新时间:2023-10-16

我正在尝试用C++编写一个程序,该程序可以在Windows上执行bash脚本,然后读取bash脚本的输出并将其存储到字符串或类似的东西中。这甚至可以在不 Windows 上安装任何额外软件的情况下实现吗?如果是这样,如何?

另外,如果我使用 Posix 库在 Linux 上编写程序,然后在 Linux 中交叉编译 Windows 的C++程序,然后将其移动到需要执行 bash 脚本的 Windows 上,它会起作用吗?

您可以使用 popen 函数。

FILE *fp;
fp = popen("bash script.sh", "r");

现在,您可以像读取文件一样读取输出。例:

char output[100];
fgets(output, sizeof(output), fp);