问题
I have this C program in which it should be given arguments like the following:
./program -i inputFile -o outputFile
and here's my related section of code
while ((c = getopt(argc, argv, "i:o:")) != -1) {
switch (c) {
case 'i':
inFile = strdup(optarg);
break;
case 'o':
outFile = strdup(optarg);
break;
default:
error_usage(argv[0]);
}
}
also here's the error_usage function:
void error_usage(char *prog)
{
fprintf(stderr, "Usage: %s -i inputfile -o outputfile\n", prog);
exit(1);
}
How should I modify my case statement in a way that if I run my program like the following:
./program
it gives me the following error?
Usage: prog -i inputfile -o outputfile
回答1:
Before you call getopt
, check argc
if ( argc == 1 )
{
fprintf(stderr, "... ");
return -1;
}
回答2:
See inFile
and outFile
to NULL
Then after your getopts loop check to see if either is still NULL. If they are then print the usage message and exit
if (inFile == NULL || outFile == NULL)
error_usage(argv[0]);
来源:https://stackoverflow.com/questions/18952077/how-to-handle-exceptions-when-we-give-no-argument-to-a-c-executable-program