繁体   English   中英

Getopt 无法识别命令行 arguments(C 程序)

[英]Getopt not recognizing command line arguments (C program)

我正在 CentOS linux 中创建 C 程序,我无法让我的 getopt 从命令行识别 ZDBC11CAABD5BDA99FD77E6FB4。 我对 linux 和 C 比较陌生。

我得到的错误是'找不到命令'我使用 gcc 编译文件并使用./testFile 编译命令执行是: gcc mathwait.c 然后 -testFile

感谢您的帮助!

void help()
{
 printf("The options for this program are:\n ");
 printf("-h - walkthrough of options and program intent\n ");
 printf("This program forks off a single child process to do a task\n ");
 printf("The main process will wait for it to complete and then do\n");
 printf("some additional work\n");
}

int main(int argc, char **argv)
{
 int option;
 while((option = getopt(argc, argv, "h")) != -1)
{
  switch(option)
 {
  case 'h':
   help();
  break;
  default:
   help();
  break;
 }
}
}
  1. 您缺少两个 header 文件:
#include <stdio.h>
#include <unistd.h>

并且您缺少退货声明:

return 0;
  1. 每个 getopt(3) 手册页:

如果没有更多选项字符,getopt() 返回 -1

这意味着如果您不提供任何 arguments getopt()将返回 -1 并且您的while()循环不会被执行并且您的程序将退出。 如果您使用-h调用程序,将执行第一个案例,否则(意味着任何其他参数)将执行default案例。

  1. 我假设这是测试代码,否则当你在所有情况下都做同样的事情时,没有必要进行切换。

  2. 格式化对可读性很重要:

#include <stdio.h>
#include <unistd.h>

void help() {
    printf(
        "The options for this program are:\n"
        "-h - walkthrough of options and program intent\n"
        "This program forks off a single child process to do a task\n"
        "The main process will wait for it to complete and then do\n"
        "some additional work\n"
    );
}

int main(int argc, char **argv) {
    int option;
    while((option = getopt(argc, argv, "h")) != -1) {
        switch(option) {
            case 'h':
                help();
                break;
            default:
                help();
                break;
        }
    }
    return 0;
}

你说:

编译命令是: gcc mathwait.c -o testFile然后./testFile

如果您运行./testFile ,则您没有提供任何 arguments。 跑:

./testFile -h

现在您为getopt()处理提供了一个选项。 如果您运行./testFile -x ,您会收到一条关于无法识别的选项'x'的消息,然后是来自help() function 的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM