简体   繁体   English

在C中使用getopt不检测任何选项(在Linux中)

[英]Detecting no option with getopt in C (in Linux)

I want to write a simple C program using terminal in Linux. 我想在Linux中使用终端编写一个简单的C程序。 I don't know how to check if no option was provided during program executing: 我不知道如何检查程序执行期间是否未提供任何选项:

./program.a

Here's my script: 这是我的脚本:

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

int main(int argc, char **argv)
{
 int opt;

           while ((opt = getopt (argc, argv, "il:")) != -1)
               switch (opt) 
                {
                case 'i':
                   printf("This is option i");           
                break;
                case 'l':
                   printf("This is option l");
                break;
                default:
                   fprintf(stderr,"Usage: %s [-i] opt [-l] opt\n",argv[0]); 
                }

if (argc == -1) {
printf("Without option");
}
}

So the output with: 因此输出结果如下:

./program.a

Should be: 应该:

"Without option"

I tried to do it with "if" and set argc to -1, 0 or NULL, but it doesn't work. 我尝试使用“ if”将argc设置为-1、0或NULL,但是它不起作用。 I know that in bash I can use sth like that: if [ $# -eq 0] or if [-z "${p}" ], to check if no option was provided, but in CI have no idea how to check that... 我知道在bash中我可以这样使用sth:if [$#-eq 0]或if [-z“ $ {p}”],检查是否未提供任何选项,但在CI中不知道如何检查那...

I have a second question too: is it possible to somehow combine bash functions with C code in one script/program? 我也有第二个问题:是否可以在一个脚本/程序中以某种方式将bash函数与C代码结合起来?

Thanks for any hints. 感谢您的任何提示。 B

我认为如果不传递任何参数(选项)来启动,则需要检查argc编号,您的argc将为1,否则为1 + count(选项)。

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

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