【问题标题】:Using a shell script in C++在 C++ 中使用 shell 脚本
【发布时间】:2014-04-18 19:37:50
【问题描述】:

我必须编写一个 C++ 程序来将命令行参数传递给 shell 脚本。 我的代码会编译,但是当我尝试使用参数运行程序时,它会开始一个新行,就像它在等待输入而不是将参数传递给脚本一样。

这是我的 C++ 代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>

char command[50];

int main(int argc, char *argv[])
{

        sprintf(command, "%s %s", "./findName", argv[1]);
        system(command);
}

我正在像这样从 unix 终端运行文件:

./findName someargument

【问题讨论】:

  • 我很困惑;您是在尝试从 shell 运行 C++ 程序,还是尝试从 C++ 程序启动 shell 命令?
  • 你是怎么调用c++程序的?当你在没有参数的情况下运行 findName 会发生什么?
  • 为什么要使用固定缓冲区来寻找错误?使用std::string
  • @CoffeeandCode return 0 隐含在 main()
  • @Angew 哦,我会记住的。虽然我永远不会鼓励它。

标签: c++ bash shell


【解决方案1】:

工作.cpp

#include <iostream>
#include <cstdio>
#include <cstdlib>

char command[50];

int main(int argc, char *argv[])
{

        sprintf(command, "%s %s", "./findname", argv[1]);
        system(command);
}

然后找到名字

#!/bin/bash
echo "hello $1"

在终端

$gcc -o working working.cpp
$./working world
hello world

您显然不能将您的 cpp 程序的名称放在系统命令中,因为它会永远调用自己。

【讨论】:

  • 我正在使用 make 文件进行编译,然后以与此相同的方式输入它,但它不起作用
  • @user2929674 你的 cpp 程序叫什么名字,你的脚本叫什么名字?
  • findname 是否可执行?您收到的错误消息是什么?
  • @逃避cpp程序是findName.cpp,脚本是findName.sh
  • 那么你应该在你的 cpp 程序中调用 system 时调用 findName.sh ,否则你会从你的 cpp 程序中调用你的 cpp 程序,导致无限循环的调用。
【解决方案2】:

findName.sh 有什么作用?你所说的没有关于等待输入的内容。此外,如果这是 shell 脚本的名称,则应将其放入 sprintf 行,大写 N.sh 在末尾等等......

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2023-03-07
    • 2018-02-27
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    相关资源
    最近更新 更多