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
and you are missing a return statement:
This means if you don’t supply any arguments
getopt()
will return -1 and youwhile()
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) thedefault
case will be executed.I assume this is test code, otherwise there is no point of having a switch when you do the same thing in all cases.
Formatting matters for readability:
You say:
If you run
./testFile
, you are not providing any arguments. Run: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 thehelp()
function.