How to handle exceptions when we give no argument

2019-08-25 06:22发布

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

2条回答
你好瞎i
2楼-- · 2019-08-25 06:49

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]);
查看更多
做个烂人
3楼-- · 2019-08-25 07:10

Before you call getopt, check argc

if ( argc == 1 )
{
  fprintf(stderr, "... ");
  return -1;
}
查看更多
登录 后发表回答