skip to Main Content

I am creating a C program in CentOS linux, and I cannot get my getopt to recognize arguments from the command line. I am relatively new to linux and C.

The error I get is ‘command not found’
I compiled the file using gcc and executing with ./testFile
compile command was: gcc mathwait.c -o testFile and then ./testFile

thanks for your help!

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

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

2

Answers


    1. You are missing the two header files:
    #include <stdio.h>
    #include <unistd.h>
    

    and you are missing a return statement:

    return 0;
    
    1. Per getopt(3) man page:

    If there are no more option characters, getopt() returns -1

    This means if you don’t supply any arguments getopt() will return -1 and you while() loop is not being executed and your program will exit. If you call your program with -h the first case will be executed, otherwise (meaning any other arguments) the default case will be executed.

    1. I assume this is test code, otherwise there is no point of having a switch when you do the same thing in all cases.

    2. Formatting matters for readability:

    #include <stdio.h>
    #include <unistd.h>
    
    void help() {
        printf(
            "The options for this program are:n"
            "-h - walkthrough of options and program intentn"
            "This program forks off a single child process to do a taskn"
            "The main process will wait for it to complete and then don"
            "some additional workn"
        );
    }
    
    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;
    }
    
    Login or Signup to reply.
  1. You say:

    compile command was: gcc mathwait.c -o testFile and then ./testFile

    If you run ./testFile, you are not providing any arguments. Run:

    ./testFile -h
    

    Now you provide an option for getopt() to process. If you ran ./testFile -x, you’d get a message about an unrecognized option 'x' and then the information from the help() function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search