Search code examples
clinuxbashgetoptgetopts

Detecting no option with getopt in C (in Linux)


I want to write a simple C program using terminal in Linux. 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. 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 C I have no idea how to check that...

I have a second question too: is it possible to somehow combine bash functions with C code in one script/program?

Thanks for any hints. B


Solution

  • I think you need check argc number if you don't pass any argument(option) for starting, your argc will 1, otherwise 1 + count(options).