【问题标题】:How to make a console app that excutes a command only when called如何制作仅在调用时才执行命令的控制台应用程序
【发布时间】:2020-01-17 08:12:03
【问题描述】:

我正在开发一个功能类似于 Windows 任务管理器但作为控制台应用程序的项目。到目前为止,我设法让应用程序呈现菜单,并且根据用户的选择,应用程序运行特定的功能。

现在,我正在考虑让应用程序使用命令执行某些功能,例如,假设我们有命令close -all。这应该关闭所有打开的窗口。

事实上,我有一些关于如何处理命令和调用相应函数的信息,我认为使用词法分析器生成标记然后使用解析器调用函数,如果我弄错了,请纠正我。

但是,只有当我的应用程序在 cmd 中运行时,我才能使用这些命令。我想要的是随时调用像wg close all(wg 是应用程序名称)这样的命令,然后可能继续运行其他cmd 命令,比如mkdircd

【问题讨论】:

  • 在我看来,您需要创建一个包含您的自定义命令的 bash 脚本..

标签: c++ cmd console console-application


【解决方案1】:

这听起来像是您需要 main(int argc, char* argv[]) 方法提供的 C++ 程序的基本功能(如果需要,请参阅此文档:https://en.cppreference.com/w/cpp/language/main_function)。

argc 是参数的数量,argv 是一个包含参数值的数组。我假设您的应用程序使用 Qt 或某个库构建了一个 GUI,如果以批处理模式运行,您将不需要启动它们。

根据您需要处理的参数的复杂性,您可以使用非常基本的结构来解析参数。

示例伪代码


main(argc, argv) {

  if (argc == 0) {
    startProgramInNormalGUIMode();
    exit(0);
  }

  // This could be a sub method "parse(argc, argv)"

  String parameter="";
  Boolean executed=false;

  for (i=0; i < argc; ++i) {

    if element == "close" {
      set parameter = argv[i+1];
      i++;  // skip next element which was the parameter

      // myCloseOperation would check if parameter is 
      // "all" for example and closes all windows
      // or treat any other value as window title for 
      // example and closes only the matching window.
      myCloseOperation(parameter);
      set executed = true;
    }

    if element == "operation2" {
      set parameter = argv[i+1];
      i++;

      myOperation2Method(parameter);
      set executed = true;
    }
  }

  if (executed == false) {
    showSyntaxErrorMessage();
    exit(1);
  }

  exit(0);

}

上面的伪代码假定每个操作都有一个标识名称,并且后面只有一个参数。您可以更改代码以允许零个参数或多个参数,并相应地更改 i 增量。

您还可以添加检查参数或操作字符串是否以破折号或斜杠或您想要的其他前缀开头。

还假设一个操作及其参数可能在命令行中多次出现,并且每次出现都会被执行。例如,wg close aWindowTitle close anotherWindowTitle close all 将被解析为有效并执行三个关闭操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2023-04-08
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多