c++ - 通过 C++ 程序将命令传递到 shell 脚本
问题描述
我正在尝试通过 C++ 程序将命令传递到我的 shell 脚本中,但我根本不熟悉 C++,虽然我知道我必须使用 system(),但我不确定如何有效地设置它。
#include <iostream>
#include <stdlib.h>
int main() {
system("./script $1");
return 0;
}
这是我目前拥有的。
似乎我不能在系统命令中使用位置参数,但我不确定还能做什么。我正在尝试通过 C++ 程序将参数传递给脚本。
解决方案
如果您只想调用“./script”,并将 C++ 程序的第一个参数作为脚本的第一个参数传递,您可以这样做:
#include <iostream>
#include <string>
#include <stdlib.h>
int main(int argc, char ** argv)
{
if (argc < 2)
{
printf("Usage: ./MyProgram the_argument\n");
exit(10);
}
std::string commandLine = "./script ";
commandLine += argv[1];
std::cout << "Executing command: " << commandLine << std::endl;
system(commandLine.c_str());
return 0;
}
推荐阅读
- google-app-engine - 使用服务帐户的 GCP 服务器到服务器身份验证
- php - 将字符串转换为 JSON 对象
- azure - 在客户租户中创建 Azure AD 应用程序
- reactjs - 即使我在浏览器中写入路由中定义的确切路径,React 组件也不会加载
- python - Python tkinter Mac 和 windows
- python-3.x - 为什么返回与字符串不匹配?
- javascript - 响应式 Bootstrap/Cytoscape 集成
- c - Gstreamer:从时间字符串中去除时间偏移部分
- python - 有没有办法将烧瓶中的 HTML 代码作为字符串传递?
- google-sheets - 从游戏数据中显示排名的数据透视表