This question already has an answer here:
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
See
inFile
andoutFile
to NULLThen after your getopts loop check to see if either is still NULL. If they are then print the usage message and exit
Before you call
getopt
, checkargc