在 C 中使用 getopt 检测不到任何选项(在 Linux 中)
Detecting no option with getopt in C (in Linux)
我想在 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 代码合并为一个 script/program?
感谢任何提示。
B
我想你需要检查 argc 如果你没有传递任何参数(选项)开始,你的 argc 将为 1,否则 1 + count(选项)。
我想在 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 代码合并为一个 script/program?
感谢任何提示。 B
我想你需要检查 argc 如果你没有传递任何参数(选项)开始,你的 argc 将为 1,否则 1 + count(选项)。