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 intent\n ");
printf("This program forks off a single child process to do a task\n ");
printf("The main process will wait for it to complete and then do\n");
printf("some additional work\n");
}
int main(int argc, char **argv)
{
int option;
while((option = getopt(argc, argv, "h")) != -1)
{
switch(option)
{
case 'h':
help();
break;
default:
help();
break;
}
}
}
CodePudding user response:
- You are missing the two header files:
#include <stdio.h>
#include <unistd.h>
and you are missing a return statement:
return 0;
- 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.
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:
#include <stdio.h>
#include <unistd.h>
void help() {
printf(
"The options for this program are:\n"
"-h - walkthrough of options and program intent\n"
"This program forks off a single child process to do a task\n"
"The main process will wait for it to complete and then do\n"
"some additional work\n"
);
}
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;
}
CodePudding user response:
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.