0

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

0

2 Answers 2

2

Before you call getopt, check argc

if ( argc == 1 )
{
  fprintf(stderr, "... ");
  return -1;
}
Sign up to request clarification or add additional context in comments.

15 Comments

And what if only one of the options was missing?
you can check argc, if argc == 1 when there are no arguments, or argc == 2 if there is only one argument.
And what if the user repeated the -i argument? Then there would be the correct number of arguments, but the usage would still be wrong.
then he would need to analyze the results after getopt, but that was not the question.
@MonaJalal you would need to copy argv[0] into a buffer and then remove the path.
|
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]);

2 Comments

Simply getopt can do the job
@P0W Then you should supply an answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.