gpt4 book ai didi

c - 在 C 中使用 getopt 检测没有选项(在 Linux 中)

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:44 25 4
gpt4 key购买 nike

我想在 Linux 中使用终端编写一个简单的 C 程序。我不知道如何检查程序执行期间是否没有提供任何选项:

./program.a

这是我的脚本:

#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");
}
}

所以输出:

./program.a

应该是:

"Without option"

我尝试用“if”来完成它,并将 argc 设置为 -1、0 或 NULL,但它不起作用。我知道在 bash 中我可以这样使用:if [ $# -eq 0] or if [-z "${p}"], 检查是否没有提供选项,但在 C 中我不知道如何检查那...

我还有第二个问题:是否可以在一个脚本/程序中以某种方式将 bash 函数与 C 代码结合起来?

感谢任何提示。B

最佳答案

我认为你需要检查 argc 如果你没有传递任何参数(选项)开始,你的 argc 将为 1,否则 1 + count(选项)。

关于c - 在 C 中使用 getopt 检测没有选项(在 Linux 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com